weixin_33739646 2018-09-19 10:49 采纳率: 0%
浏览 39

遍历ajax值

I have some values that are returned to ajax from backend. The problem in this code is that when I do console.log(myRows) the values in cells are undefined.

  $(document).on('click', ".myButton", function () {



        $.ajax({
            type: "POST",
            url: "Administration.aspx/GetMyCollection",
            data: JSON.stringify({ 'Parameter': Parameter }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data.d.length > 0) {
                    var myRows = "";

                    $.each(data, function (i, values) {

                        values.ObjectID;
                        values.ObjectName;
                        values.ObjectValue;
                        values.Object;
                        console.log(values);

                        myRows += "<tr><td>" + values[1].ID + "</td><td>" + values[1].ObjectName + "</td><td>" + values[1].ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
                        console.log(myRows);
                    });

                }
                console.log("Saved!");
            },
            error: function () {
                console.log("Not Saved!");
           }

        });
    });

But when I change the code and add values[1], the values are displayed correctly.

 myRows += "<tr><td>" + values[1].ID + "</td><td>" + values[1].ObjectName + "</td><td>" + values[1].ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";

I need help to change the code so it will loop through all 9 (from 1 to 9) values and places the results in myRows cells so all the values can be displayed.

Json code:

d   […]
0   {…}
ObjectID      1
ObjectName    Vegas
ObjectValue   234
Object        Arizona
1   {…}
ObjectID      2
ObjectName    Chicago
ObjectValue   211
Object        Montana
2   {…}
ObjectID      3
ObjectName    Livepool
ObjectValue   123
Object        London
... 

Thanks in advance !

  • 写回答

3条回答 默认 最新

  • weixin_33698823 2018-09-19 10:51
    关注

    As you are iterating over the array, values will hold the object. Hence, you do not need to use values[i] or values[1]. Additionally, it seems you have data in data.d and hence, should iterate on that.

    Hence, you can update your code to following

    $.each(data.d, function (i, values) {
      myRows += "<tr><td>" + values.ObjectID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values.Object + "</td></tr>";
    });
    console.log(myRows);
    

    Note, add your log after the each block to see complete set of rows.

    评论

报告相同问题?