loop through a json object in ajax response
本问题已经有最佳答案,请猛点这里访问。
我是json的新手所以我从我的ajax调用中获得了json响应
现在我被困在循环json对象
这是我的json
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "0": { "image":"http://test.com/systems.jpg", "anchor_tag_link":"http://test.com/1", "title":"Oct-Dec-2013" }, "1": { "image":"http://test.com/energy.jpg", "anchor_tag_link":"http://test.com/1", "title":"July-Sept-2013" }, "pages": 2 } |
谁能帮忙
您可以使用for-in循环,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | var obj = { "0": { "image":"http://test.com/systems.jpg", "anchor_tag_link":"http://test.com/1", "title":"Oct-Dec-2013" }, "1": { "image":"http://test.com/energy.jpg", "anchor_tag_link":"http://test.com/1", "title":"July-Sept-2013" }, "pages": 2 } for(var prop in obj) { var item = obj[prop]; console.log(item); } |
请注意,您将获取日志中的项目,因为除了数字属性之外,您还将获得
将JSON响应保存在变量中
1 2 3 4 5 6 7 8 9 10 11 12 13 | var variable = { "0" : { "image" :"http://test.com/systems.jpg", "anchor_tag_link" :"http://test.com/1", "title" :"Oct-Dec-2013" }, "1" : { "image" :"http://test.com/energy.jpg", "anchor_tag_link" :"http://test.com/1", "title" :"July-Sept-2013" }, "pages" : 2 }; |
然后使用jquery循环它
1 2 3 4 | $.each(variable, function(index, value) { alert(value.image); alert(value.anchor_tag_link); }); |
你可以这样做。
1 2 3 4 5 | var json = JSON.parse(data);// here data is your response for (var key in json) { alert(json[key].image);// other also in the same way. } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | JQuery: var JSON = { "0": { "image":"http://test.com/systems.jpg", "anchor_tag_link":"http://test.com/1", "title":"Oct-Dec-2013" }, "1": { "image":"http://test.com/energy.jpg", "anchor_tag_link":"http://test.com/1", "title":"July-Sept-2013" }, "pages": 2 }; if(JSON.pages >0) { for(var i=0; i<JSON.pages; i++) { $('table').append('<tr><td>'+JSON[i].title+'</td><td>'+JSON[i].image+'</td><td>'+JSON[i].anchor_tag_link+'</td></tr>'); } } HTML: <table border="1"></table> |
你可以通过javascript对象循环遍历这个:
1 2 3 4 5 | for(var arg in object) { object.hasOwnProperty(arg) { process(object[arg]); } } |
请尝试以下代码。 您只需要用JSON数组替换"yourJSONObject"。
1 2 3 4 5 | $.each( yourJSONObject, function( keyImg, valImg ) { image = valImg[0]; anchor_tag_link = valImg[1]; title = valImg[2]; }); |
问候,
例1:
1 2 3 4 5 | success: function(responseData) { for (var key in responseData) { alert(responseData[key]); } } |
例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var data = '{"name":"mkyong","age": 30,"address": {"streetAddress":"88 8nd Street","city":"New York"},"phoneNumber": [{"type":"home","number":"111 111-1111"},{"type":"fax","number":"222 222-2222"}]}'; var json = JSON.parse(data); alert(json["name"]); //mkyong alert(json.name); //mkyong alert(json.address.streetAddress); //88 8nd Street alert(json["address"].city); //New York alert(json.phoneNumber[0].number); //111 111-1111 alert(json.phoneNumber[1].type); //fax alert(json.phoneNumber.number); //undefined |
示例代码