JavaScript的:如何判断AJAX响应是否是JSON [英] Javascript: How to tell whether AJAX response is JSON

查看:102
本文介绍了JavaScript的:如何判断AJAX响应是否是JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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和您指定的的dataType 属性= http://api.jquery.com/jQuery.ajax> $。阿贾克斯() 来电 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).

这篇关于JavaScript的:如何判断AJAX响应是否是JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆