jquery 检查 JSON var 是否存在

jquery check if json var exist

本文关键字:是否 存在 var JSON 检查 jquery      更新时间:2023-09-26

如何使用jquery检查getJSON之后生成的json中是否存在键/值?

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(); }
    });
}

基本上我需要一种方法来查看 d.failed 是否存在,如果它 = 'true',那么不要继续循环推送。

你不需要jQuery,只需要JavaScript。您可以通过以下几种方式执行此操作:

  • typeof d.failed - 返回类型("未定义"、"数字"等)
  • d.hasOwnProperty('failed') - 以防万一它是继承的
  • 'failed' in d - 检查它是否曾经被设置过(甚至未定义)

您也可以对 d.failed: if (d.failed) 进行检查,但如果 d.failed 未定义、null、false 或零,这将返回 false。为了简单起见,为什么不做if (d.failed === 'true')呢?为什么要检查它是否存在?如果这是真的,只需返回或设置某种布尔值。

参考:

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

昨天找到了这个。CSS 像 JSON 的选择器

http://jsonselect.org/

你可以对if语句使用javascript习语,如下所示:

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

就这么简单。在您的情况下,它应该是:

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

具有讽刺意味的是,正如OP在问题中所写的那样,这读作"如果d.failed存在并设置为'true'"。