49

当我们使用 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');
4

2 回答 2

90

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

对于 jQuery > 1.3

success: function(res, status, xhr) { 
  alert(xhr.getResponseHeader("myHeader"));
}
于 2012-07-12T20:16:47.910 回答
3

对于 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'));
  });
}
于 2018-11-20T11:22:42.273 回答