jQuery $.each loop and json data
I can't seem to get this working, i am retrieving some json data, and just trying to loop through it an append it to a DIV. here is my code:
HOW THE JSON IS RETURNED (PHP开发者_开发技巧)
{"list":[{"subscribe":"example"},{"subscribe":"example2"},{"subscribe":"example3"},{"subscribe":"example4"},{"subscribe":"example5"}]}
MY JSON CALL USING JQUERY
$.getJSON("article.php",function(data)
$.each(data.list, function(i,data) {
var listData = "<li>" + data.subscribe + "</li>";
$('#lists').append(listData);
});
});
I am not retrieving any errors in the console, but nothing is happening, i know the call is successful, am i doing the .each loop correctly? can anyone please help?
Maybe you can try this:
$.each(data.list, function(i, item) {
var listData = "<li>" + item.subscribe + "</li>";
$('#lists').append(listData);
});
Just change function(i, data)
to function(i, item)
.
By reusing the variable name data
in the way that you are, you are not actually looping through the array as you expect to.
I personally haven't used $.each
to loop through an array because I always just do a for
loop, so you can try this:
$.getJSON("article.php", function (d) {
var listsDiv = $("#lists");
for (var i = 0; i < d.list.length; i++) {
listsDiv.append("<li>" + d.list[i].subscribe + "</li>");
};
});
I'm 99% confident that it should work for what you need. Also, it's better to have a variable to your div outside of the loop and append in the loop because right now your code is traversing the DOM for that div for each object in your JSON list.
Also, I'm not sure if you're truncating the JSON response, but you may want to attach a 'success' property and check for that. So you're code would be upgraded to this:
$.getJSON("article.php", function (d) {
if (d.success) {
var listsDiv = $("#lists");
for (var i = 0; i < d.list.length; i++) {
listsDiv.append("<li>" + d.list[i].subscribe + "</li>");
};
} else {
// Do something else to notify the user that the data could not be retrieved.
};
});
Seems you got a syntax error. A { is missing after first line i.e the starting { for "function(data)" in first line
精彩评论