Getting the actual URL after a POST which redirect

2019-03-13 06:09发布

I am following the PRG (Post-Redirect-Get) pattern in my web application, and use something like the following for doing most of my POSTs:

$.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: ' + ??);
    },
});

I need to get the URL AFTER any redirection has occurred, i.e. the URL of the final GET that the .ajax() function called. For example a POST to A.html may redirect to either B.html or C.html (always via 302's). How do I get the final URL?

I am using jquery 1.5.1, and using a proxy have witnessed that jquery is silently following the redirects - which I am happy with. I don't care about any of the URLs which responded with 302's - I would just like to know the URL of the final request at the time that .ajax()'s "success:" or "complete:" hooks are fired.

3条回答
手持菜刀,她持情操
2楼-- · 2019-03-13 06:12

A better solution is to supply jQuery's ajax with a custom xhr object like this:

var xhr = new XMLHttpRequest();

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

Then you can access the current URL in any callback

success: function () {
    alert('You are now at URL: ' + xhr.responseURL);
}
查看更多
够拽才男人
3楼-- · 2019-03-13 06:24

I finally solved this issue by adding an additional header into all my responses (eg "X-MYAPP-PATH: /Admin/Index").

My javascript could thus be changed to the following:

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

I still believe however that jquery should be able to give me the current URL, so I consider this a hack.

查看更多
手持菜刀,她持情操
4楼-- · 2019-03-13 06:27

First try to figure out the status code that is being returned by the redirection (its usually > 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"));
        }
    },

One more point to be noted that the order of execution: success\failure --> statusCode function --> Complete

查看更多
登录 后发表回答