Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在ajaxSuccess期间确定响应是否为JSON的理想方法_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript 在ajaxSuccess期间确定响应是否为JSON的理想方法

Javascript 在ajaxSuccess期间确定响应是否为JSON的理想方法,javascript,jquery,ajax,Javascript,Jquery,Ajax,在$.ajaxSuccess()函数中,我需要确定响应是否为json。目前我正在这样做: $('body').ajaxSuccess(function(evt, xhr, settings) { var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/); if(contType && contType.length == 2 && contType[1].

在$.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一样解析它,并捕获任何错误。另见

如果您需要多种不同的响应类型中的一种(例如,它可能是json,也可能只是文本,等等),那么您可能需要变得更复杂。我会使用xhr.getResponseHeader(“内容类型”)。有关处理内容类型的详细信息,请参见

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

您可能可以使用jQuery.parseJSON来尝试解析它。如果引发异常,则它不是有效的json


我总是发现以下方法很管用:

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

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

如果您需要数据表单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;
    }
});
$.ajax({
数据类型:“json”,//数据类型很重要
键入:“post”,
网址:orifinalurl,
数据:reqParam,
}).完成(功能(数据){
//响应是有效的json数据。
}).错误(函数(jqxhr,异常){
if(jqxhr.status==0){
msg='无法连接到服务器。请检查您的网络连接';
}else if(jqxhr.status==404){
msg='找不到请求的页面。错误-404';
}else if(jqxhr.status==500){
msg='内部服务器错误-500]';
}else if(异常==='parserrror'){
msg='Requested JSON parse failed';
}else if(异常==='timeout'){
msg='Request timeout error';
}否则如果(异常==='abort'){
msg='Request aborted';
}否则{
msg='Uncaught Error.n'+jqxhr.responseText;
}
});

这正是我想要的。不知何故,我错过了
getResponseHeader
方法,这将使我免于执行这种混乱的正则表达式如果您确定服务器总是返回正确的内容类型头,并且您只想查看响应文本是否为JSON,那么此解决方案比使用jQuery.parseJSON()更好,因为它的计算强度较小。但是,如果您确实计划对响应文本执行任何操作,则需要使用jQuery.parseJSON()。请注意,内容类型也可以包含编码信息。例如,“应用程序/json”;字符集=utf-8'。看见
  if (xhr.getResponseHeader('Content-Type') !== 'application/json') {
    // Something other than JSON was returned
  }
$.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;
    }
});