在我的$ .ajaxSucess()函数中,我需要找出响应是否为json。目前我这样做:
$('body').ajaxSuccess(function(evt, xhr, settings) {
var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){
...
有更好的方法吗?
答案 0 :(得分:25)
假设您期待json,我只是尝试像json一样解析它并捕获任何错误。另请参阅jQuery.parseJSON。
try {
jQuery.parseJSON(response);
} catch(error) {
// its not json
}
如果您期望许多不同的响应类型中的一种(即它可能是json或者它可能只是文本等),那么您可能需要变得更复杂。我使用xhr.getResponseHeader(“content-type”)。有关处理内容类型的一些详细信息,请参阅this blog post。
$.ajax({
type: "POST",
url: "/widgets",
data: widgetForm.serialize(),
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf(‘html’) > -1) {
widgetForm.replaceWith(response);
}
if (ct.indexOf(‘json’) > -1) {
// handle json here
}
}
});
答案 1 :(得分:8)
我总是发现以下工作正常:
if (xhr.getResponseHeader('Content-Type') !== 'application/json') {
// Something other than JSON was returned
}
您是否遇到过需要额外逻辑的情况?
答案 2 :(得分:1)
var a={"k":"v"};
var b="k";
try{
$.parseJSON(b);
}catch(e){alert('Not JSON')}
答案 3 :(得分:0)
您可以使用jQuery.parseJSON来尝试解析它。如果引发异常,则它无效json。
答案 4 :(得分:0)
如果你期望数据形成ajax响应,你可以通过跟随ajax调用来处理它:
$.ajax({
dataType: "json", //dataType is important
type: 'post',
url: orifinalurl,
data: reqParam,
}).done(function(data){
//response is valid json data.
}).error(function(jqxhr, exception){
if (jqxhr.status === 0) {
msg='Can not connect to server. Please check your network connection';
} else if (jqxhr.status == 404) {
msg='Requested page not found. <b>Error -404</b>';
} else if (jqxhr.status == 500) {
msg='Internal Server Error <b>Error -500</b>].';
} else if (exception === 'parsererror') {
msg='Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg='Request Time out error.';
} else if (exception === 'abort') {
msg='Request aborted.';
} else {
msg='Uncaught Error.n' + jqxhr.responseText;
}
});