I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with!
What does the line
xhr.send('')
do? Why is it needed if we already have the GET request line establishing contact with the server?
(My other questions are related to closures, which I am still trying to fully grasp...)What exactly is being passed as a parameter to
function(myxhr)
?Could someone explain at what point in the program xhr gets passed to the anonymous function, which has (xhr) as a parameter? For instance, is it after
xhr.open
is executed?Why is the function
function(myxhr)
necessary? If it's for creating closure, why is closure needed here?If indeed
xhr
is passed as a parameter tofunction(myxhr)
, why is there a need to change the parameter name fromxhr
tomyxhr
?If it is true that
xhr
is passed as a parameter tofunction(myxhr)
, then is the parameter(xhr)
of the anonymous function being passed as the parametermyxhr
in the call tofunction(myxhr)
when the anonymous function is invoked?
Here's a snippet of the code:
function request(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (function(myxhr){
return function() {
callback(myxhr);
}
})(xhr);
xhr.open('GET', url, true);
xhr.send('');
}
request (
'http://www.phpied.com/files/jsoop/content.txt',
function (o){
document.getElementById('text').innerHTML = o.responseText;
}
);
request(
'http://www.phpied.com/files/jsoop/content.html',
function(o) {
document.getElementById('html').innerHTML = o.responseText;
}
);
request(
'http://www.phpied.com/files/jsoop/content.xml',
function(o){
document.getElementById('xml').innerHTML =
o.responseXML.getElementsByTagName('root')[0].firstChild.nodeValue;
}
);