-2

我有以下 JSON 作为响应:

{
    "responseHeader": {
        "status": 0,
        "QTime": 1
    },
    "spellcheck": {
        "suggestions": [
            "goo",
            {
                "numFound": 4,
                "startOffset": 0,
                "endOffset": 3,
                "suggestion": [
                    "good",
                    "google",
                    "google's",
                    "goodbye"
                ]
            },
            "collation",
            "good"
        ]
    }
}

现在基于查询,我有时可能会得到这个 JSON:

{
    "responseHeader": {
        "status": 0,
        "QTime": 1
    }
}

当“拼写检查”不存在时,我想检查我的 jQuery 代码。因为否则它会引发异常并且脚本停止执行。

我试过这个:

if(typeof(response.spellcheck)!=='undefined')

但它抛出异常。

帮助。

4

4 回答 4

1

你只能说if(response && response.spellcheck)...

于 2013-07-08T11:24:05.080 回答
1

尝试hasOwnProperty

if(response.hasOwnProperty("spellcheck")) {
    ...
}
于 2013-07-08T11:24:15.830 回答
0

尝试if (response && response.hasOwnProperty('spellcheck') && response.spellcheck) {/*your code here*/}

于 2013-07-08T11:49:05.957 回答
-1

将你的 json 分配给一个变量 say response 并检查它的长度

if ( response['spellcheck'].length < 1 ) {
// it's empty
}
于 2013-07-08T11:29:54.937 回答