I’ve been smashing my head against this all day – but I finally got something working consistently and reliable, so I better damn well document it. This is as good a place as any, and hopefully it will be useful to others.
I needed to make an Ajax call, so I turned to my good friend XMLHttpRequest. One wrinkle was that I needed to pass in a parameter to it… so I tried:
var test = "bar"; req = new XMLHttpRequest(); req.open("GET", myURL, true); req.foo = test; req.onreadystatechange = function() { if (this.readyState != 4) return; if (this.status == 200) { alert(this.foo); // should print out "bar" } } req.send(null);
For the most part this worked. Except every now and then… when it didn’t. Most annoyingly, it failed pretty consistently when I was trying to use it within a nested Ajax call (complicated code, don’t ask.. it’s not interesting).
I’m not sure why it doesn’t work to be honest. From my understanding, req.foo should just instantiate a new foo member variable of the XMLHttpRequest object I just created and set it to be referenced via ‘this.foo’ inside any member function. I’m guessing it’s something to do with the scoping of onreadystatechange being set to the reference of an anonymous function so the anonymous function isn’t actually part of the XMLHttpRequest object and thus doesn’t have access to its member variables. What’s frustrating is that it works most of the time. A consistent failure model would actually be more helpful here.
Anyway, enough blabbering, here’s what seemed to work for me:
var test = "bar"; req = new XMLHttpRequest(); req.open("GET", myURL, true); req.onreadystatechange = function(foo) { return function() { if (this.readyState != 4) return; if (this.status == 200) { alert(foo); }; }(test); } req.send(null);
Now that works reliably for me 100% of the time.
Source:http://whacked.net/2007/11/27/passing-parameters-to-xmlhttprequests-onreadystatechange-function/
thx for the article, here good karma for you.