How to get Response Header location from jQuery Get?

前端 未结 3 1159
猫巷女王i
猫巷女王i 2020-12-31 05:21

So I am trying to get the location from a header response via jQuery get. I tried using getResponseHeader(\'Location\') and getAllResponseHeaders() but they both seem to ret

相关标签:
3条回答
  • 2020-12-31 05:39

    The headers will be available when the asynchronous request returns, so you will need to read them in the success callback:

    $.ajax({
        type: "GET",
        url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
        success: function(data, status, xhr) {
            console.log(xhr.getResponseHeader('Location'));
        }
    });
    
    0 讨论(0)
  • 2020-12-31 05:46

    for some headers in jQuery Ajax you need to access XMLHttpRequest object

    var xhr;
    var _orgAjax = jQuery.ajaxSettings.xhr;
    jQuery.ajaxSettings.xhr = function () {
      xhr = _orgAjax();
      return xhr;
    };
    
    $.ajax({
        type: "GET",
        url: 'http://example.com/redirect',
        success: function(data) {
            console.log(xhr.responseURL);
        }
    });
    

    or using plain javascript

    var xhr = new XMLHttpRequest();
    xhr.open('GET', "http://example.com/redirect", true);
    
    xhr.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        console.log(xhr.responseURL);
      }
    };
    
    xhr.send();
    
    0 讨论(0)
  • 2020-12-31 05:47

    jQuery abstracts the XMLHttpRequest object in a so-called "super set" that does not expose the responseURL field. It's in their docs where they talk about the "jQuery XMLHttpRequest (jqXHR) object"

    For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
    
    readyState
    responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
    status
    statusText
    abort( [ statusText ] )
    getAllResponseHeaders() as a string
    getResponseHeader( name )
    overrideMimeType( mimeType )
    setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
    statusCode( callbacksByStatusCode )
    No onreadystatechange mechanism is provided, however, since done, fail, always, and statusCode cover all conceivable requirements.
    

    As you can see there is no way to get hold of the response URL because the jqXHR API does not expose it

    0 讨论(0)
提交回复
热议问题