Reputation: 4621
In the following js snippet
request = new XMLHttpRequest
request.open('GET', '/my/url', true)
request.send()
request.onload = function() {
data = JSON.parse(this.response)
}
should the assignment of the on load be before the send() to avoid a race condition. Or does the browser deal with it for you (by firing the on load when you get round to assigning it).
Upvotes: 1
Views: 197
Reputation: 10617
Your request should look more like:
var request = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
request.open('GET', '/my/url');
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
console.log(request.responseText);
}
}
request.send();
To further answer your question request.send()
should happen last, because if the response comes back before the function is assigned to request.onreadystatechange
, there could be a problem, although it's very unlikely that the response would be that fast.
Upvotes: 1