我遇到附加json的问题。它打印了多个未定义的内容,我不确定原因是什么。
我的代码:
$("button").click(function() {
$.getJSON("https://api.myjson.com/bins/503aj", function(obj) {
$.each(obj, function(key, test) {
$("ul").append("<div>" + test.CustomerRef + "</div>" + "<div>" + obj.CustomerName + "</div>" + "<div>" + test.DelAddress1 + "</div>");
});
});
});
链接js小提示显示问题;
https://jsfiddle.net/7vshmzj7/
为什么这样做?什么是可能的解决方法?
答案 0 :(得分:3)
你回来的JSON看起来像这样:
{
"AddressData": {
"OrderNo": "4200",
"CustomerRef": "A1011",
"DelAddress1": "4 Test Road",
"DelAddress2": "Testing Lane",
"DelAddress3": "Testland",
"DelAddress4": "UK",
"DelPostCode": "DB11 8DA"
},
"CustomerRef": "A1011",
"CustomerName": "John Doe",
"CustomerData": {
"Email": "JohnDoe2500@gmail.com",
"Phone": "07785442"
}
}
这不是您必须使用$.each
循环播放的内容,而使用$.each
循环播放它是问题所在。
直接使用它:
$("button").click(function() {
$.getJSON("https://api.myjson.com/bins/503aj", function(obj) {
$("ul").append("<div>" + obj.CustomerRef + "</div>" + "<div>" + obj.CustomerName + "</div>" + "<div>" + obj.AddressData.DelAddress1 + "</div>");
});
});
请注意,您访问的三个字段的访问方式如下:
obj.CustomerRef
obj.CustomerName
obj.AddressData.DelAddress1