检测 Ajax 请求中的重定向?

我想使用 jQuery 来获取一个 URL,并显式检查它是否响应了302重定向,但是 没有遵循重定向。

JQuery 的 $.ajax似乎总是遵循重定向。我怎样才能防止这种情况发生,并且不遵循它就能看到重定向呢?

有很多类似于“ jquery ajax redirect”的问题,但是它们似乎都涉及到完成一些其他的目标,而不仅仅是直接检查服务器提供的状态。

115801 次浏览

The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events


@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
request = event.request
if request.is_xhr:
event.response.headers['X-Response-URL'] = request.url

Welcome to the future!

Right now we have a "responseURL" property from xhr object. YAY!

See How to get response url in XMLHttpRequest?

However, jQuery (at least 1.7.1) doesn't give an access to XMLHttpRequest object directly. You can use something like this:

var xhr;
var _orgAjax = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = function () {
xhr = _orgAjax();
return xhr;
};


jQuery.ajax('http://test.com', {
success: function(responseText) {
console.log('responseURL:', xhr.responseURL, 'responseText:', responseText);
}
});

It's not a clean solution and i suppose jQuery team will make something for responseURL in the future releases.

TIP: just compare original URL with responseUrl. If it's equal then no redirect was given. If it's "undefined" then responseUrl is probably not supported. However as Nick Garvey said, AJAX request never has the opportunity to NOT follow the redirect but you may resolve a number of tasks by using responseUrl property.

You can now use fetch API/ It returns redirected: *boolean*