0

我想区分服务器响应、基于 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

我究竟做错了什么?

ps resp 有时是 json,有时是纯文本。

4

1 回答 1

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;
    }
于 2013-11-14T12:56:25.133 回答