我正在使用简单的JSON Ajax请求来获取一些JSON数据。 但是我一直尝试使用JSON对象时遇到以下问题:
未捕获的TypeError:无法读取未定义的属性“长度”
$(document).on('pageinit', '#home', function() {
$.ajax({
url: "http://localhost/documents.json",
dataType: "json",
type: 'GET',
async: true,
success: function(result) {
//ajax.parseJSON(result);
$.each(result, function(idx, obj) {
alert(obj.name);
});
},
error: function(request, error) {
alert('Network error has occurred please try again!' + ' ' + request + ' ' + error);
}
});
});
我的JSON文件有效,看起来像这样:
{
"books": [{
"id": "01",
"name": "info",
"dateiname": "info.pdf"
}, {
"id": "02",
"name": "agb",
"dateiname": "agb.pdf"
}, {
"id": "03",
"name": "raumplan",
"dateiname": "raumplan.pdf"
}, {
"id": "04",
"name": "sonstiges",
"dateiname": "sonstiges.pdf"
}, {
"id": "05",
"name": "werbung",
"dateiname": "werbung.pdf"
}]
}
答案 0 :(得分:0)
您应该执行以下操作:
if(result && result["books"]) {
$.each(result["books"], function(idx, obj) {
alert(obj.name);
});
}
答案 1 :(得分:0)
jQuery.each
值,则 undefined
会出现此错误。但result
无法定义,或jQuery
会抛出JSON解析错误。至少result
是一个空对象{}
(或一个空数组[]
)。
您的代码从未读过任何内容的length
。所以我假设你的错误在你的代码中的其他地方。
仔细检查控制台中的错误。你应该有错误的确切行。还有堆栈。
但是代码中仍然存在错误。你应该这样:
$.each(result.books, function(idx, obj) {
alert(obj.name);
});