Как получить местоположение заголовка ответа из jQuery Get?
Итак, я пытаюсь получить местоположение из ответа заголовка через jQuery get. Я попытался использовать getResponseHeader ('Location') и getAllResponseHeaders(), но оба они возвращают значение null.
Здесь мой текущий код
$(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);
});
Ответы
Ответ 1
Заголовки будут доступны, когда возвращается асинхронный запрос, поэтому вам нужно будет прочитать их в обратном вызове успеха:
$.ajax({
type: "GET",
url: 'http://searchlight.cluen.com/E5/Login.aspx?URLKey=uzr7ncj8)',
success: function(data, status, xhr) {
console.log(xhr.getResponseHeader('Location'));
}
});
Ответ 2
для некоторых заголовков в jQuery Ajax вам нужно получить доступ к объекту 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);
}
});
или используя простой 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();
Ответ 3
jQuery абстрагирует объект XMLHttpRequest в так называемом супер наборе, который не отображает поле responseURL. Это в своих документах, где они говорят о "объекте jQuery XMLHttpRequest (jqXHR)"
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.
Как вы видите, нет способа получить URL-адрес ответа, потому что API jqXHR не раскрывает его