JavaScript的:如何判断AJAX响应是否是JSON如何判断、JavaScript、JSON、AJAX

由网友(折月煮酒゜)分享简介:我有一个AJAX请求预计JSON响应。I've got an AJAX request that expects JSON in response.但有一种可能性,即得到什么回报可能不是JSON,而是一个HTML错误页面(不幸的是,响应类型200)。But there's a possibility that w...

我有一个AJAX请求预计JSON响应。

I've got an AJAX request that expects JSON in response.

但有一种可能性,即得到什么回报可能不是JSON,而是一个HTML错误页面(不幸的是,响应类型200)。

But there's a possibility that what gets returns may not be JSON, but rather an HTML error page (unfortunately, with response type 200).

我如何知道响应是否JSON或不?

How can I tell whether the response is JSON or not?

(我使用jQuery,是否有帮助。但我不能使用任何插件。)

(I'm using jQuery, if that helps. But I can't use any plugins.)

推荐答案

好吧,如果你正在使用jQuery和您指定的 $。阿贾克斯() 来电 JSON 则jQuery将尝试解析JSON,如果它不是JSON应该叫错误()回调。

Well, if you are using jQuery and you specify the dataType property of the $.ajax() call to json then jQuery will try to parse the JSON, and if it isn't JSON should call the error() callback.

$.ajax({
    url: '/my/script.ext',
    dataType: 'json',
    success: function(data, textStatus, jqXHR) { /*YAYE!!*/ },
    error: function(jqXHR, textStatus, errorThrown) { /*AWWW... JSON parse error*/ }
});

修改

对于任何不使用jQuery的土地在这里,其基本思想是通过尝试解析它作为JSON和捕获错误:

For anyone not using jQuery that lands here, the basic idea is to try and parse it as json and catch the error:

var data = 'some_data';

try {
    data = JSON.parse(data);
} catch(e) {
    //JSON parse error, this is not json (or JSON isn't in your browser)
}

//act here on the the parsed object in `data` (so it was json).
阅读全文

相关推荐

最新文章