简体   繁体   中英

Possible HTTP Request states after form submit

I'm trying to submit a form and get the results inpage using AJAX. I call a JS function onsubmit which makes the AJAX call, and includes this code:

        request=new XMLHttpRequest();
        /* set up request here */
        request.onreadystatechange=function() {
        if (request.readyState == 4 && request.status == 200) {
            /* do what I need */
            alert('Success');
        } else {
            /* do what I need */
            alert('Failed');
        }
    }

However, the Failed alert shows up multiple times (3 at least) before the Success one, so I guess I'm getting many different statuses before the successful one? How can I check which ones I get, and what to expect when the submission is failed? Thanks.

You only ever get one status, but you get multiple states .

Check to see if the readyState is 4 or 0 (since either of those states indicate that there is no more of the response to wait for).

Then throw an error if it is 0 or test the status if it is 4 .

If the readyState is any other value, then ignore it (unless you want to do stuff in other states).

The request goes through four phases. The readyStates. Every time the readystate updates it fires the event. 0 indicates a failure and 4 indicates that the request has finished. the status returns the http code. 200 indicates success. There was an answer and it returned a request body . All other codes indicate there was something wrong on the server side. Eg. 404, 403, or 500. You can safely ignore the other readystates . But catch any status other than 200 as failure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM