我收到了一个AJAX请求,该请求需要JSON作为响应.
但是,有可能得到的返回可能不是JSON,而是一个HTML错误页面(不幸的是,响应类型为200).
How can I tell whether the response is JSON or not?
(如果有帮助的话,我正在使用jQuery.但我不能使用任何插件.)
我收到了一个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).