Form that makes browser redirect when accessed by either a regular form submit or an Ajax request - is this possible?

后端 未结 8 1548
孤城傲影
孤城傲影 2021-01-06 08:22

I have a web page with a form. When the user submits the form, I want the server to make the browser redirect to a different page from the form action. Right now, I am doing

8条回答
  •  别那么骄傲
    2021-01-06 09:12

    HTTP 302 response are consumed silently by XmlHttpRequest implementations (e.g. jQuery's ajax function). It's a feature.

    The way I've solved this in the past is to detect for XmlHttpRequests and issue a "Content-Location" header (rather than a "Location" header). The most cross-library way of doing this is to check for the "X-Requested-With" http header in your server-side code (jQuery, Prototype, Mootools among others set this):

    if (@$_SERVER['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest') {
        header('Content-Location: ' . $redirect_url);
    } else {
        header('Location: ' . $redirect_url);
    }
    

    You still need to special-case your client-side code:

    $.ajax({
        // ...
        complete: function(xhr) {
            var redirect_url = xhr.getResponseHeader("Content-Location");
            if (redirect_url) {
                window.location = redirect_url;
            }
        }
    })
    

提交回复
热议问题