简体   繁体   中英

AJAX onreadystatechange: navigate away and save changes at same time

When a user clicks a link, I would like to send an AJAX request to save the contents of the current page, and navigate away at the same time.

Typically the window is trying to navigate away, all AJAX requests get the "stop" button, but that may or may not mean that the server is processing the request. If the AJAX is aborted to soon, the changes will not be saved.

The valid readystates according to W3Schools

1: server connection established
2: request received
3: processing request
4: request finished and response is ready

I should I wait for number 2 or number 3 to ensure the request goes through on major browsers before navigating away?

I acknowledge the risk that by not confirming a successful save in number 4, I risk not letting the user know about a failure in saving changes,, But the code is very stable, so once the server receives the request, I am almost 100% sure that if the changes are not saved, the user will have no recourse anyway (post deleted or locked or something like that, and the changes are not that important anyway).

But the only problem is, if there is an Internet Connection Failure, I need to at least know about that failure in major browsers.

Do I have to wait for number 4 to know about that?

Assuming I don't even care about connection failures, which one should I wait for?

Yes wait for 4 and check the response. You could pass back something from your server in the POST / GET to say success, then change window.location. Be sure to preventDefault if you're clicking a link to trigger your ajax.

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