how to loop through json array in jquery?

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

I have a php page from which I get response in json:

[{'com':'something'},{'com':'some other thing'}] 

I want to loop it and append each to a div.

This is what I tried:

var obj = jQuery.parseJSON(response); $.each(obj.com, function(key,value) {   alert(key+':'+value); } 

This alerts as undefined, and also response is the json array..

Please help.

回答1:

Your array has default keys(0,1) which store object {'com':'some thing'} use:

var obj = jQuery.parseJSON(response); $.each(obj, function(key,value) {   alert(value.com); });  


回答2:

Try this:

var data = jQuery.parseJSON(response); $.each(data, function(key, item)  {    console.log(item.com); }); 

or

var data = $.parseJSON(response);  $(data).each(function(i,val)  {     $.each(val,function(key,val)   {           console.log(key + " : " + val);        }); }); 


回答3:

You are iterating through an undefined value, ie, com property of the Array's object, you should iterate through the array itself:

$.each(obj, function(key,value) {    // here `value` refers to the objects  }); 

Also note that jQuery intelligently tries to parse the sent JSON, probably you don't need to parse the response. If you are using $.ajax(), you can set the dataType to json which tells jQuery parse the JSON for you.

If it still doesn't work, check the browser's console for troubleshooting.



回答4:

var data=[{'com':'something'},{'com':'some other thing'}]; $.each(data, function() {   $.each(this, function(key, val){     alert(val);//here data        alert (key); //here key    }); }); 


回答5:

you can get the key value pair as

<pre> function test(){     var data=[{'com':'something'},{'com':'some other thing'}];     $.each(data, function(key,value) {     alert(key);   alert(value.com);     });     } </pre> 


回答6:

Try this:

for(var i = 0; i < data.length; i++){     console.log(data[i].com) } 


回答7:

try this

var events = [];  alert(doc); var obj = jQuery.parseJSON(doc);       $.each(obj, function (key, value) {      alert(value.title); 

});



回答8:

Or else You can try this method

var data = jQuery.parseJSON(response); $.each(data, function(key,value) {    alert(value.Id);    //It will shows the Id values });  


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