我怀疑我的问题是由于我的JSON字符串的结构。它似乎在JSON对象中有一个JSON对象。
这是我的JSON格式:
[
{"subject":{"title":"java","id":"1","desc":"Basic java programming"},
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}
}
这是我的jquery代码:
var items = [];
$.getJSON('theurl', function(data) {
$.each(data, function(key, subject) {
alert(subject); //returning me "[object Object]"
$('#tempresult').append('<p>'+ subject +'</p>'); //returning me "[object Object]"
});
});
答案 0 :(得分:3)
您发布了一些格式错误的JSON。我假设你的元素被正确关闭为:
[
{"subject":{"title":"java","id":"1","desc":"Basic java programming"}},
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}}
]
看起来你想要$('#tempresult').append('<p>'+ subject.subject.desc +'</p>');
data[0]
就是这个对象:
{"subject":{"title":"java","id":"1","desc":"Basic java programming"}}
data[1]
就是这个对象:
{"subject":{"title":"objective c","id":"2","desc":"Introduction to objective c"}}
data[0].subject
就是这个对象:
{"title":"java","id":"1","desc":"Basic java programming"}
data[0].subject.desc
就是这样:
"Basic java programming"
答案 1 :(得分:1)
您的示例JSON有点糟糕(缺少}
)。
否则,试试这个:
$.each(data, function(key, subject) {
alert(subject.subject.title);
});
答案 2 :(得分:1)
您的主题变量是json对象。 您必须指定主题属性才能获得值
alert(subject.subject.id);
alert(subject.subject.title);
Alert(subject.subject.desc);