0

我的请求 ajax 与 json_encode:

[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"}, 
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]

var string = JSON.stringify(data);

var obj = $.parseJSON(string);

console.log(string);

var idHome = obj.idHome;

var photo = obj.Photo;


console.log(obj.idHome);

console.log(obj.Photo);

解析json的问题

控制台日志:

[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]

undefined

undefined
4

2 回答 2

2

您的 json 是一个包含三个对象的数组。

尝试

console.log(obj[0].idHome);
console.log(obj[0].Photo);

更多信息: http ://www.w3schools.com/json/json_syntax.asp

于 2013-06-18T18:53:40.053 回答
2

它是一个数组,所以你需要循环,有很多方法可以做到这一点。

for (i = 0; i < obj.length; i++) {
    console.log(obj[i].idHome);
    console.log(obj[i].Photo);
}

或者:

obj.forEach(function(val) {
    console.log(val.idHome);
    console.log(val.Photo);
});

或者:

for (var i in obj) {
    console.log(obj[i].idHome);
    console.log(obj[i].Photo);
}

jQuery使用:

 $.each(obj, function(_, val){
    console.log(val.idHome);
    console.log(val.Photo);
 });

等等....

于 2013-06-18T18:54:49.303 回答