在使用jquery重定向的POST后获取实际URL .ajax()

我在我的Web应用程序中遵循PRG(Post-Redirect-Get)模式,并使用类似以下内容来执行大多数POST:

$.ajax({ type: 'POST', url: 'A.html', data: '....', statusCode: { 302: function() { alert("302"); // this is never called }, 200: function() { alert("200"); }, }, success: function (data, textstatus) { alert('You are now at URL: ' + ??); }, error: function (data) { }, complete: function (jqXHR, textstatus) { alert('You are now at URL: ' + ??); }, }); 

我需要在任何重定向发生后获取URL,即.ajax()函数调用的最终GET的URL。 例如,对A.html的POST可以重定向到B.html或C.html(总是通过302的)。 我如何获得最终的URL?

我正在使用jquery 1.5.1,并且使用代理已经见证了jquery正在默默地遵循重定向 – 我很满意。 我不关心用302响应的任何URL – 我只想知道.ajax()的“success:”或“complete:”钩子被触发时的最终请求的URL。

我最后通过在我的所有回复中添加一个额外的标题来解决这个问题(例如“X-MYAPP-PATH:/ Admin / Index”)。

因此我的javascript可以更改为以下内容:

 success: function (data, textstatus, xhrreq) { alert('You are now at URL: ' + xhrreq.getResponseHeader("X-MYAPP-PATH")); }, 

我仍然相信jquery应该能够给我当前的URL,所以我认为这是一个黑客。

一个更好的解决方案是提供jQuery的ajax和一个自定义的xhr对象,如下所示:

 var xhr = new XMLHttpRequest(); $.ajax({ url: '/url', type: 'post', data: '...', xhr: function() { return xhr; } }); 

然后,您可以在任何回调中访问当前URL

 success: function () { alert('You are now at URL: ' + xhr.responseURL); } 

首先尝试找出重定向返回的状态代码(通常> 300)。

 success: function (data, textstatus, xhrReq) { //if the status is greater than 300 if(xhrReq.status > 300) { alert('You are now at URL: ' + xhrRequest.getHeader("Location")); } }, 

还有一点需要注意的是执行顺序:success \ failure – > statusCode function – > Complete