如何在jquery中循环json数组?
我有一个php页面,我在json中得到了响应:
[{'com':'something'},{'com':'some other thing'}]
我想循环它并将每个附加到div。
这是我试过的:
var obj = jQuery.parseJSON(response); $.each(obj.com, function(key,value) { alert(key+':'+value); }
这是undefined
警报,响应是json数组..
请帮忙。
你的数组有默认键(0,1),它存储对象{'com':'some thing'}
使用:
var obj = jQuery.parseJSON(response); $.each(obj, function(key,value) { alert(value.com); });
试试这个:
var data = jQuery.parseJSON(response); $.each(data, function(key, item) { console.log(item.com); });
要么
var data = $.parseJSON(response); $(data).each(function(i,val) { $.each(val,function(key,val) { console.log(key + " : " + val); }); });
您正在迭代undefined
值,即Array对象的com
属性,您应该遍历数组本身:
$.each(obj, function(key,value) { // here `value` refers to the objects });
另请注意,jQuery会智能地尝试解析发送的JSON,可能您不需要解析响应。 如果你使用$.ajax()
,你可以将dataType
设置为json
,告诉jQuery为你解析JSON。
如果仍然无效,请检查浏览器的控制台以进行故障排除。
var data=[{'com':'something'},{'com':'some other thing'}]; $.each(data, function() { $.each(this, function(key, val){ alert(val);//here data alert (key); //here key }); });
你可以得到键值对
function test(){ var data=[{'com':'something'},{'com':'some other thing'}]; $.each(data, function(key,value) { alert(key); alert(value.com); }); }
试试这个:
for(var i = 0; i < data.length; i++){ console.log(data[i].com) }
var data = [ {"Id": 10004, "PageName": "club"}, {"Id": 10040, "PageName": "qaz"}, {"Id": 10059, "PageName": "jjjjjjj"} ]; $.each(data, function(i, item) { alert(data[i].PageName); }); $.each(data, function(i, item) { alert(item.PageName); });
或者您可以尝试这种方法
var data = jQuery.parseJSON(response); $.each(data, function(key,value) { alert(value.Id); //It will shows the Id values });
试试这个
var events = []; alert(doc); var obj = jQuery.parseJSON(doc); $.each(obj, function (key, value) { alert(value.title);
});