jQuery $.each 循环和 json 数据
我似乎无法正常工作,我正在检索一些 json 数据,然后尝试循环遍历它并将其附加到 DIV 中。这是我的代码:
如何返回 JSON (PHP)
{"list":[{"subscribe":"example"},{"subscribe":"example2"},{"subscribe":"example3"},{"subscribe":"example4"},{"subscribe":"example5"}]}
使用 JQUERY 进行我的 JSON 调用
$.getJSON("article.php",function(data)
$.each(data.list, function(i,data) {
var listData = "<li>" + data.subscribe + "</li>";
$('#lists').append(listData);
});
});
我没有在控制台中检索到任何错误,但什么也没有发生,我知道调用成功,我是否正确执行 .each 循环?有人可以帮忙吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许你可以尝试这个:
只需将
function(i, data)
更改为function(i, item)
即可。通过按照您现在的方式重用变量名
data
,您实际上并没有像您期望的那样循环遍历数组。Maybe you can try this:
Just change
function(i, data)
tofunction(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.我个人没有使用
$.each
来循环数组,因为我总是只执行for
循环,所以你可以尝试这个:我有 99% 的信心它应该可以满足您的需要。另外,最好在循环外部为 div 添加一个变量并在循环中追加,因为现在您的代码正在为 JSON 列表中的 每个 对象遍历该 div 的 DOM。
另外,我不确定您是否正在截断 JSON 响应,但您可能想要附加一个“成功”属性并进行检查。所以你的代码将升级为:
I personally haven't used
$.each
to loop through an array because I always just do afor
loop, so you can try this: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:
看来你有语法错误。第一行后缺少 {,即第一行中“function(data)”的起始 {
Seems you got a syntax error. A { is missing after first line i.e the starting { for "function(data)" in first line