我想区分服务器响应,基于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,有时是纯文本。
答案 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;
}