jQuery $.each loop and json data

。_饼干妹妹 提交于 2019-12-11 06:54:57

问题


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?


回答1:


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.




回答2:


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.
    };
});



回答3:


Seems you got a syntax error. A { is missing after first line i.e the starting { for "function(data)" in first line



来源:https://stackoverflow.com/questions/5973717/jquery-each-loop-and-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!