jQuery - 获取AJAX响应头

52

使用jQuery发出ajax请求时,如何访问响应头?我根据一些网站的建议尝试了下面的代码。但是xhr对象为空。在此上下文中,我看到了一个xhr对象,但它没有访问响应头的方法。

function SampleMethod() {
  var savedThis = this;
  this.invokeProcedure = function(procedurePath) {
    $.ajax({
      type: "GET",
      url: procedurePath,
      dataType: "json",
      success: function(data,status,xhr) savedThis.resultSetHandler(data,status,xhr);}
    });
  }

  this.resultSetHandler=function(data,status,xhrObj){
    //Handle the result
  }

  this.errorHandler = function(args) {
    //Handle the result
  }

}

var sampleObj = new SampleMethod();
sampleObj.invokeProcedure('url');
2个回答

94

为了与XMLHttpRequest保持向后兼容,jqXHR对象将公开以下属性和方法:getAllResponseHeaders()getResponseHeader()。详情请参考$.ajax()文档:http://api.jquery.com/jQuery.ajax/

适用于jQuery版本大于1.3。

success: function(res, status, xhr) { 
  alert(xhr.getResponseHeader("myHeader"));
}

2
getAllResponseHeaders()只提供以下内容:content-length: 0 content-type: text/html; charset=UTF-8但在Chrome Network中,我看到了更多的内容:Access-Control-Allow-Credentials: fa... ... Access-Control-Allow-Origin: https://sho... Access-Control-Max-Age: 1728... Connection: keep-alive Content-Length: 0 Content-Security-Policy: frame-ancestors 'none' Content-Type: text/html; charset=UT Refresh: 0; url=https://sec... Server: nginx/1.1... Set-Cookie: lang=ru; ...等等。我需要Refresh,但无法获取它。 - maxkuku
与上述评论相同,不起作用,仅可用内容类型和内容长度。 - Illegal Operator

4

对于 jQuery 3 及以上版本

以下是解决方案,适用于我:

//I only created this function as I am making many ajax calls with different urls and appending the result to different divs
function makeAjaxCall(requestType, urlTo, resultAreaId){
  var jqxhr = $.ajax({
    type: requestType,
    url: urlTo
  });

  //this section is executed when the server responds with no error 
  jqxhr.done(function(){
  });

  //this section is executed when the server responds with error
  jqxhr.fail(function(){
  });

  //this section is always executed
  jqxhr.always(function(){
    //here is how to access the response header
    console.log("getting header " + jqxhr.getResponseHeader('testHeader'));
  });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接