4

I tested two kinds of doing XHR:

1.

xhr.onreadystatechange = function() {

            if (this.readyState == 4 && xhr.status !== 500) {

                function getElementByXpath(path) {

2.

xhr.onload= function() {

                function getElementByXpath(path) {

and don't realized any difference. Could somebody point me to it? Or is there realy no one?

Evgeniy
  • 2,337
  • 2
  • 28
  • 68
  • Does this answer your question? [Is onload equal to readyState==4 in XMLHttpRequest?](https://stackoverflow.com/questions/9181090/is-onload-equal-to-readystate-4-in-xmlhttprequest) – Henke May 13 '21 at 09:47

1 Answers1

6

A readystatechange event fires every time the readyState changes (which is several times).

A load event fires only when the request has completed successfully.

In your example you add some extra tests to your readystatechange handler to test if it has reached the final state (4 (unless there are certain kinds of error in which case it will be 0)) and to make sure it isn't a 500 error. There are other errors which would not trigger a load event.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Does it mean the result of `xhr.onLoad` is always data, while the result of `readystatechange` could be, data, undefined and 0? – Evgeniy Mar 15 '20 at 20:49
  • 2
    No. You've confusing the `readyState` with the `responseText`. – Quentin Mar 15 '20 at 20:51