在ajaxSuccess期间找出响应是否为JSON的理想方法

Ideal way to find out if response is JSON during ajaxSuccess

本文关键字:JSON 理想 方法 是否 响应 ajaxSuccess      更新时间:2023-09-26

在我的$. ajaxsuccess()函数中,我需要找出响应是否为json。当前我正在做的是:

$('body').ajaxSuccess(function(evt, xhr, settings) {
    var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
    if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){    
...

有更好的方法吗?

假设您期望json,我只是尝试像json一样解析它并捕获任何错误。参见jQuery.parseJSON

try {
    jQuery.parseJSON(response);
} catch(error) {
    // its not json
}

如果你期待一个不同的响应类型(即它可能是json或它可能只是文本等),那么你可能需要变得更复杂。我会使用xhr.getResponseHeader("content-type")。有关处理内容类型的详细信息,请参阅这篇博文。

$.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
        } 
    }
});

我总是发现下面的工作很好:

  if (xhr.getResponseHeader('Content-Type') !== 'application/json') {
    // Something other than JSON was returned
  }

你是否遇到了需要在你的帖子中添加额外逻辑的情况?

var a={"k":"v"};
var b="k";
try{
 $.parseJSON(b);
}catch(e){alert('Not JSON')}

您可以使用jQuery。parseJSON来尝试解析它。如果引发异常,则该文件无效json.

http://api.jquery.com/jQuery.parseJSON/

如果您期望数据表单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;
    }
});