Jquery check if json var exists

How can I use jquery to check if a key / value exists as a result of json after 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 exists and if it = 'true', and then not continue cyclic clicks.

+4
source share
3 answers

You do not need jQuery for this, just JavaScript. You can do this in several ways:

  • typeof d.failed - returns type ('undefined', 'Number', etc.)
  • d.hasOwnProperty('failed') - just in case, he inherited
  • 'failed' in d - check if it is ever installed (even before undefined)

You can also check for d.failed: if (d.failed) , but this will return false if d.failed is undefined, null, false or zero. To make it simple, why not do if (d.failed === 'true') ? Why check it out? If this is true, just return or install some Boolean language.

Link:

http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

+11
source

Found it yesterday. CSS as a selector for JSON

http://jsonselect.org/

+1
source

You can use the javascript idiom for if-statements, for example:

 if (d.failed) { // code in here will execute if not undefined or null } 

Just. In your case, it should be:

 if (d.failed && d.failed != 'true') { myPush(); } 

Ironically, it reads "if d.failed exists and has the value" true ", as OP wrote in the question.

0
source

All Articles