Nik*_*lik 22 jquery json loops
我有一个php页面,我在json中得到响应:
[{'com':'something'},{'com':'some other thing'}]
Run Code Online (Sandbox Code Playgroud)
我想循环它并将每个附加到div.
这是我试过的:
var obj = jQuery.parseJSON(response);
$.each(obj.com, function(key,value) {
alert(key+':'+value);
}
Run Code Online (Sandbox Code Playgroud)
这个警告为undefined,并且响应是json数组..
请帮忙.
Del*_*ell 49
您的数组具有存储对象{'com':'some thing'}
使用的默认键(0,1):
var obj = jQuery.parseJSON(response);
$.each(obj, function(key,value) {
alert(value.com);
});
Run Code Online (Sandbox Code Playgroud)
试试这个:
var data = jQuery.parseJSON(response);
$.each(data, function(key, item)
{
console.log(item.com);
});
Run Code Online (Sandbox Code Playgroud)
要么
var data = $.parseJSON(response);
$(data).each(function(i,val)
{
$.each(val,function(key,val)
{
console.log(key + " : " + val);
});
});
Run Code Online (Sandbox Code Playgroud)
您正在迭代一个undefined值,即com数组对象的属性,您应该迭代数组本身:
$.each(obj, function(key,value) {
// here `value` refers to the objects
});
Run Code Online (Sandbox Code Playgroud)
另请注意,jQuery 会智能地尝试解析发送的 JSON,可能您不需要解析响应。如果您使用$.ajax(),您可以设置dataType来json告诉 jQuery 为您解析 JSON。
如果仍然不起作用,请检查浏览器的控制台以进行故障排除。
var data = [ \n {"Id": 10004, "PageName": "club"}, \n {"Id": 10040, "PageName": "qaz"}, \n {"Id": 10059, "PageName": "jjjjjjj"}\n];\n\n$.each(data, function(i, item) {\n alert(data[i].PageName);\n});\xe2\x80\x8b\n\n$.each(data, function(i, item) {\n alert(item.PageName);\n});\xe2\x80\x8b\nRun Code Online (Sandbox Code Playgroud)\n\n或者你可以尝试这个方法
\n\nvar data = jQuery.parseJSON(response);\n$.each(data, function(key,value) {\n alert(value.Id); //It will shows the Id values\n}); \nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
98756 次 |
| 最近记录: |