2012-07-11 168 views
31

当我们使用jQuery发起ajax请求时,我们如何访问响应标头?根据某些网站提供的建议,我尝试使用下面的代码。但是xhr对象即将为空。在这种情况下,我看到一个xhr对象。但它没有访问响应头的方法。jQuery - 获取AJAX响应标头

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'); 

回答

64

对于使用XMLHttpRequest向后兼容,一个jqXHR对象将 暴露出以下属性和方法:getAllResponseHeaders()getResponseHeader()。 从$就()DOC:http://api.jquery.com/jQuery.ajax/

的jQuery> 1.3

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