jquery check if json var exist
How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?
function myPush(){
$.getJSON("client.php?action=listen",function(d){
d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
$('#display').prepend(d.chat_msg+'<br />');
开发者_运维问答 if(d.failed != 'true'){ myPush(); }
});
}
Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.
You don't need jQuery for this, just JavaScript. You can do it a few ways:
typeof d.failed
- returns the type ('undefined', 'Number', etc)d.hasOwnProperty('failed')
- just in case it's inherited'failed' in d
- check if it was ever set (even to undefined)
You can also do a check on d.failed: if (d.failed)
, but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')
? Why check if it exists? If it's true, just return or set some kind of boolean.
Reference:
http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/
Found this yesterday. CSS like selectors for JSON
http://jsonselect.org/
You can use a javascript idiom for if-statements like this:
if (d.failed) {
// code in here will execute if not undefined or null
}
Simple as that. In your case it should be:
if (d.failed && d.failed != 'true') {
myPush();
}
Ironically this reads out as "if d.failed exists and is set to 'true'" as the OP wrote in the question.
精彩评论