简体   繁体   中英

in AJAX (XMLHttpRequest) is it better to use eventListener or readyStateChange?

I was re-watching a video from WWDC12 on advanced effects with HTML5 and noticed that for the demo they used req.addEventListener("load",callback,true) rather than the usual onreadystatechange .

What are the differences between the load event and state=4 status=200 situation?
Is it the same load event being fired or two different ones?

The load event only indicates that the request was a network success, not necessarily an HTTP success. An Ajax request with always either fire a load event or an error event, indicating the success or failure of the network transaction (as part of the Progress Events specification):

  • The error event fires when the network fetch fails due to the server being down or on an inaccessible domain (ie, the request is blocked by the same-origin policy).

  • Otherwise, load fires, regardless of the HTTP code returned.

The load or error event always fires last, after the last readstatechange event has fired, so you can be sure that the load or error callback is running with xhr.readyState == 4 and xhr.status set to the correct HTTP response code.

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