AJAX onreadystatechange take parameters?

A

akhil.patel

I realize that this may have been asked before, but I could not find a
definitive answer.

function loadXMLDoc(url, MyFunction)
{
// use native XMLHttpRequest object
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
request.onreadystatechange = MyFunction;
request.open("GET", url, true);
request.send(null);
// use IE/Windows ActiveX version
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
if (request) {
request.onreadystatechange = MyFunction;
request.open("GET", url, true);
request.send();
}
}
}

Is there any way to script 'MyFunction' aka the callback function to
take parameters?
 
M

Martin Honnen

request.onreadystatechange = MyFunction;

Is there any way to script 'MyFunction' aka the callback function to
take parameters?

That assigment simply assigns MyFunction as the onreadystatechange event
handler. You can also dynamically create functions with a function
expression for instance so that you probably want e.g.
request.onreadystatechange = function () {
if (request.readyState == 4) {
MyFunction(arg1, arg2);
}
};
where the onreadystatechange handler is an anonymous function created by
a function expression. That function is then being called by the
implementation of the XMLHTTP request object and in turn can of course
call other functions (like MyFunction) and pass arguments to that.
You should read up on closures then
<http://www.jibbering.com/faq/faq_notes/closures.html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top