I am using a simple JSON Ajax request to get some JSON data. But all the time I try to use the JSON object I get the following issue:
Uncaught TypeError: Cannot read property 'length' of undefined
$(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);
}
});
});
my JSON file is valid and looks like that:
{
"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"
}]
}
You should perform something like the following:
if(result && result["books"]) {
$.each(result["books"], function(idx, obj) {
alert(obj.name);
});
}
jQuery.each
can make this error if you provide a undefined
value. But result
can't be undefined or jQuery
would throw a JSON parse error. At least result
is an empty object {}
(or an empty array []
).
Your code never read the length
of anything. So i assume your error is somewhere else in your code.
Double check the error in your console. You should have the exact line of the error. And the stack too.
But there's still an error in your code. You should have this :
$.each(result.books, function(idx, obj) {
alert(obj.name);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.