If you're asking why the if
statement executes, it's because onreadystatechange
is called every time the state of the XHR request changes. There are 5 states for XHR:
- 0: UNSENT (
open()
has not been called yet) - 1: OPENED (
send()
has not been called yet) - 2: HEADERS_RECEIVED (
send()
has been called and headers and status are available) - 3: LOADING (downloading;
responseText
holds partial data) - 4: DONE (operation complete)
Because onreadystatechange
will be called when it starts loading, you're getting passed in a partial JSON file, which is extremely unlikely to validate as proper JSON. You need to check that the readyState
is 4, that is, it has finished loading:
if (xhr.readyState === 4 && xhr.status === 200 && t != tt.lastData) {
You also probably want to check that the request was successful by checking for a HTTP 200 response. For more information about XMLHttpRequest
, see this MDN article.