'length' is null or not an object? IE 8
I get the following error in IE8:
length is null or not an object
Anyone have any ideas? Feedback greatly appreciated.
function refresh() {
$.getJSON(files+"handler.php?action=view&load=update&time="+lastTimeInterval+"&username="+username+"&topic_id="+topic_id+"&t=" + (new Date()), function(json) {
if(json.length) {
for(i=0; i < json.length; i++) {
$('#list').prepend(prepare(json[i]));
$('#list-' + count).fadeIn(1500);
}
var j = i-1;
开发者_如何学C lastTimeInterval = json[j].timestamp;
}
});
}
Just check for the object being null or empty:
if (json && json.length) {
// ...
}
C'mon gang this was glaringly obvious :-)
JSON objects (returned by jQuery or otherwise) do not have a length
property. You'll need to iterate over the properties, most likely, or know the structure and simply pull out what you want:
$.getJSON( ..., ..., function( json ) {
for( var prop in json ) {
if( !json.hasOwnProperty( prop ) ) { return; }
alert( prop + " : " + json[prop] );
}
} );
Alternatively, grab a library like json2 and you'll be able to stringify the object for output/debugging.
pop the JSON in a span then clip it and paste it here so we can see it:
<span id="JSObject2">empty</span>
with the json2.js from here: (link for it at bottom of the page) http://www.json.org/js.html
myJSON = JSON.stringify(json);
$('#JSObject2').text(myJSON);
Using that, we can help you better, and you can see what you have!
What does your returned JSON look like? If you're returning an object, length might not be explicitly defined, whereas if you're returning an array, it should be defined automatically.
First thing that comes to mind is that length is not a property of whatever json is. What is the json variable supposed to be anyway?
A JSON is an object, you seem to be treating it like an array. Does it really have a length
property? Show us the JSON?
You might need to use a for..in
instead.
EDIT: Can you make the JSON from the backend structure like so?
({
"foo": []
})
精彩评论