我收到了一个AJAX请求,该请求需要JSON作为响应.

但是,有可能得到的返回可能不是JSON,而是一个HTML错误页面(不幸的是,响应类型为200).

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

(如果有帮助的话,我正在使用jQuery.但我不能使用任何插件.)

推荐答案

如果您使用的是jQuery,并且将$.ajax()调用的dataType属性指定为json,那么jQuery将try 解析JSON,如果不是,JSON应该调用error()回调.

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

EDIT

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).

Json相关问答推荐

PowerShell脚本未按预期生成预期的JSON输出

Flutter -控制器问题-JSON API

如何使用GoFr返回XML响应?

JQ:获取该值的较短语法是什么

使用快速json库编写json可以消除所有缩进

bash用jq获取第二条JSON记录

将 std::可选值存储到 json 文件 C++

Jolt 不打印任何东西

Serde JSON 反序列化枚举

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

Servicestack 返回数组而不是带有数组的对象

如何从 rails 中的 respond_to 方法生成 json?

如何在 jQuery 中循环遍历 JSON 数组?

规范化 JSON 文件

谷歌浏览器不允许我放置断点

如何向(JSON)对象的原型添加方法?

waitUntilAllTask​​sAreFinished 错误 Swift

有什么方法可以判断您安装的 gulp 版本吗?

Python 到 JSON 序列化在十进制上失败

从 Ruby 中的 JSON 文件解析并从嵌套哈希中提取数字