mowwwalker
mowwwalker

Reputation: 17334

XMLHttpRequest onload property?

I like to do as much code as possible without jquery, so for ajax requests, I've been doing something along the lines of what the MDN said:

function alertContents(httpRequest) {  
  try {  
    if (httpRequest.readyState === 4) {  
      if (httpRequest.status === 200) {  
        alert(httpRequest.responseText);  
      } else {  
        alert('There was a problem with the request.');  
      }  
    }  
  }  
  catch( e ) {  
    alert('Caught Exception: ' + e.description);  
  }  
}  

I was looking at the Google tutorial for making extensions and they used the onload of their request. Is the onload an event listening that runs when the readystate is 4 and the status 200? If not, what is it, and when do I use it instead of the above method.

Upvotes: 4

Views: 2082

Answers (1)

Omri
Omri

Reputation: 278

XHR level 2 with cross origin implements other events than onreadystatechange, which are progress events (specify the statechange); loadstart, progress, error, abort, load, loadend

you may use the onload event as pre-checked readystate 4, and go on to check the XHR status (200 -> 300 || 304 i'd imagine)

Upvotes: 2

Related Questions