检查json对象是否返回jquery错误

时间:2013-11-14 12:51:33

标签: javascript jquery json

我想区分服务器响应,基于json或纯文本。所以在我的ajax电话中我已经:

success: function(resp) {
    //
    json = $.parseJSON(resp);
    if (typeof json == "object") {
        console.dir(json);
    } else {
        console.dir(resp);
    }
    //
}

问题是,它在Parse线上打破了,所以我永远无法到达我检查typeof的行...

Uncaught SyntaxError: Unexpected token

我做错了什么?

P.S。 resp有时是json,有时是纯文本。

1 个答案:

答案 0 :(得分:2)

如果您没有收到Json,那么就无法解析它。

你应该尝试/捕捉错误:

 var response;
 try{
       response=$.parseJSON(resp);
       //if you pass this without error your json is valid json
       }catch(err){
       //handle here the resp as plain text.
       response=resp;
    }