I got this example demonstrating AJAX from Stoyan Stefanovs Object Oriented JavaScript at page 275. In this example, he is requesting three different files. I have a couple questions if any of you can help.
-
What is
xhr.send('')doing? Why do we need it? I thought GET in the line before was establishign contact with the server, so why this send?
(The other questions relate to the closure that I don`t fully understand…) -
what exactly is getting passed as a paramater to
function(myxhr)? -
regarding the anonymous function, which has (xhr) passed as a parameter, can you explain at what point in the program xhr gets passed to the anonymous function? For example, is it after
xhr.openhas taken place? -
why is function(myxhr) necessary? If it`s to create closure, why is closure necessary here?
-
is parameter
(xhr)of the anonymous function getting passed as parametermyxhrinfunction(myxhr)once the anonymous function is called? -
if 5 is true–that
xhris passed as a parameter tofunction(myxhr)–why is it necessary to change the parameter name fromxhrtomyxhr?
Sample 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;
}
);
Open just sets up the request. Send actually sends it. When you make a POST request you need to pass the to send.
The content of the variable
xhr.As soon as the function is called (which is immediately as the definition is followed by
()).It isn’t. Even if the
xhrvariable wasn’t locally scoped to therequestfunction (which it is) then it could be accessed viathis.Yes.
It isn’t. You can reuse the variable name at different scopes. It makes it less confusing though.