jQuery loop over JSON result from AJAX Success?

2019-01-01 14:21发布

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements? I have tried something like below but this does not seem to be working.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});

标签: jquery ajax json
10条回答
梦该遗忘
2楼-- · 2019-01-01 14:49

You can also use the getJSON function:

$.getJSON('/your/script.php', function(data) {
    $.each(data, function(index) {
        alert(data[index].TEST1);
        alert(data[index].TEST2);
    });
});
查看更多
孤独总比滥情好
3楼-- · 2019-01-01 14:50

This is what I came up with to easily view all data values:

var dataItems = "";
$.each(data, function (index, itemData) {
    dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);

查看更多
孤独寂梦人
4楼-- · 2019-01-01 14:51

Try jQuery.map function, works pretty well with maps.

var mapArray = {
  "lastName": "Last Name cannot be null!",
  "email": "Email cannot be null!",
  "firstName": "First Name cannot be null!"
};

$.map(mapArray, function(val, key) {
  alert("Value is :" + val);
  alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

查看更多
临风纵饮
5楼-- · 2019-01-01 14:54

you can remove the outer loop and replace this with data.data:

$.each(data.data, function(k, v) {
    /// do stuff
});

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.

查看更多
残风、尘缘若梦
6楼-- · 2019-01-01 14:54

You can also use the getJSON function:

    $.getJSON('/your/script.php', function(data) {
        $.each(data, function(index) {
            alert(data[index].TEST1);
            alert(data[index].TEST2);
        });
    });

This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.

查看更多
永恒的永恒
7楼-- · 2019-01-01 15:00

If you use Fire Fox, just open up a console (use F12 key) and try out this:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

查看更多
登录 后发表回答