2012-06-27 11 views
16

Więc próbuję uzyskać lokalizację z odpowiedzi nagłówka za pośrednictwem jQuery get. Próbowałem użyć getResponseHeader ("Lokalizacja") i getAllResponseHeaders(), ale oba wydają się zwracać wartość null.Jak uzyskać położenie nagłówka odpowiedzi z jQuery Get?

Oto mój aktualny kod

$(document).ready(function(){ 
    var geturl; 
    geturl = $.ajax({ 
     type: "GET", 
     url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)', 
    }); 
    var locationResponse = geturl.getResponseHeader('Location'); 
    console.log(locationResponse); 
}); 
+0

prawdopodobnie duplikat http://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call –

Odpowiedz

25

Nagłówki będzie dostępna, gdy asynchroniczne żądania powraca, więc trzeba będzie czytać je w 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')); 
    } 
}); 
+1

wypróbował to bez powodzenia. URL nie zwraca oświadczenia o powodzeniu. Próbowałem wydrukować to na false i bez powodzenia – raeq

+3

wypróbuj 'complete: function (xhr) {console.log (xhr.getAllResponseHeaders()); } ' – Bergi

+3

Ciągle otrzymuję pusty lub pusty ciąg http://jsfiddle.net/nNGLD// – raeq

3

dla niektórych nagłówków w Ajax jQuery, do którego należy uzyskać dostęp Obiekt XMLHttpRequest

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

lub stosując zwykły 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(); 
-1

jQuery abstrahuje obiektu XMLHttpRequest w tak zwanych „super set”, który nie narazi pole responseURL. To w ich docs gdzie mówią o „jQuery XMLHttpRequest (jqXHR) obiektu”

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. 

Jak widać nie ma sposobu, aby zdobyć URL odpowiedzi, ponieważ API jqXHR nie narażać go

Powiązane problemy