jQuery - 获取AJAX响应头

时间:2012-07-11 20:26:43

标签: jquery httpresponse

当我们使用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 个答案:

答案 0 :(得分:71)

  

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

对于jQuery> 1.3

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

答案 1 :(得分:0)

JQUERY 3及更高版本的更新2018

我知道这是一个古老的问题,但希望此解决方案将对那些找不到解决方案的人有所帮助。这是对我有用的解决方案:

//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'));
        });
    }
相关问题