web-dev-qa-db-ja.com

jQuery-get AJAX応答ヘッダー

JQueryを使用してajaxリクエストを発行するときに、応答ヘッダーにアクセスするにはどうすればよいですか?私はいくつかのサイトで与えられた提案に従って、以下のコードで試しました。ただし、xhrオブジェクトはnullになります。このコンテキストに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');
35
Apps

XMLHttpRequestとの後方互換性のために、jqXHRオブジェクトは次のプロパティとメソッドを公開します:getAllResponseHeaders()およびgetResponseHeader( )。 $ .ajax()ドキュメントから: http://api.jquery.com/jQuery.ajax/

JQuery> 1.3の場合

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

JQUERY 3以降のUPDATE 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'));
        });
    }
0
sticky_elbows