Reputation: 3923
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;
lastTimeInterval = json[j].timestamp;
}
});
}
Upvotes: 8
Views: 20385
Reputation: 413846
Just check for the object being null or empty:
if (json && json.length) {
// ...
}
C'mon gang this was glaringly obvious :-)
Upvotes: 12
Reputation: 186662
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": []
})
Upvotes: 0
Reputation: 34197
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!
Upvotes: 1
Reputation: 30442
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.
Upvotes: 1
Reputation: 581
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?
Upvotes: 0
Reputation: 83289
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.
Upvotes: 0