weixin_33720078 2018-01-02 14:19 采纳率: 0%
浏览 20

在AJAX中处理PHP标头

I am doing a form validating using AJAX. If the user completes the form correctly, it will redirect to another page, else print out errors (plain HTML).
For example: If there is an error in the form, the PHP file echos:

There is an error!

If there aren't any errors, the PHP file executes:

header("Location: http://example.com/successful"); exit();

But in AJAX, I am only handling for the plain HTML response:

success: function(response) {
_desireHTMLelment.innerHTML = response;
}

I know there is a way using json_encode(), however, I still cannot classify plain HTML and JSON.
Are there any ways I can do this? Thanks for any support!
Edit: I am using Vanilla JavaScript
This is how the system works:
User fills in the form => AJAX sends requests => PHP processes the request => Either returns an plain HTML error or redirects the page => AJAX receives the response, classify whether it is an error or HTML error => Find a correct way to handle the response

  • 写回答

2条回答 默认 最新

  • ℡Wang Yan 2018-01-02 14:27
    关注

    As Quentin mentioned, browsers automatically follow the Location header and redirect the page, in which case your Ajax response will contain the content of the new page and you will not be able to access the Location header because it was lost and replaced by the content of the new page. You can use a different name for your header.

    It seems from your code that you're using jQuery, not JavaScript Vanilla. You can access the header in jQuery like this:

    success: function(response, status, request){
        var url = request.getResponseHeader('RedirectURL'); //RedirectURL: your header's name.
    }
    

    In JavaScript Vanilla, use the getAllResponseHeaders() function of the XMLHttpRequest object to get the header:

    var headers = request.getAllResponseHeaders();
    

    But unlike jQuery, you'll have to split and process the headers by yourself.

    Once you get the url from the header, you can use:

    location.replace(url);
    

    This simulate a redirect. If you want to simulate a link click, use:

    location.href = url;
    

    Alternatively, you can send the URL in the response instead of the header. If it always starts with http, you can do something like:

    success: function(response) {
        if (response.substring(0, 4) == "http") {
            location.href = response;
        } else {
           _desireHTMLelment.innerHTML = response;
        }
    }
    

    Or you can flag it like this and look for the flag:

    RedirectURL: http://example.com/successful
    

    Or you can make it a JSON object:

    {"RedirectURL": "http://example.com/successful"}
    
    评论

报告相同问题?