I’m trying to make a xmlHttpRequest before the page body loads. When trying to assign the onreadystatechange function, this one gets called instantly, thus returning xmlHttp.readyState always to 0.
I supose I’m making the call in a wrong way. How am I supposed to assign the function correctly?
//create xmlHttp object
function CreateXmlHttp() {
try {
var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(eo) {
xmlHttp = null;
}
}
if(!xmlHttp && typeof XMLHttpRequest != "undefined") {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
//request call
function post(url, func, XML) {
var xmlHttp = CreateXmlHttp();
//problem?
xmlHttp.onreadystatechange = (function (xmlHttp, func) {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
func(xmlHttp.responseText);
}
})(xmlHttp, func);
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
if(XML==null){
XML = '';
}
xmlHttp.send(XML);
}
post('/json/checklogged', function (data) {
var jsonData = eval("(" + data + ")"); //I know, this eval is dangerous
if(jsonData.logged){
var url = '${nextUrl}';
post(url, function(data){
document.open();
document.write(data);
document.close();
});
history.pushState({}, '', url);
}
});
Don’t execute the function at all. You’re assigning a listener, i.e. creating (not executing) the function that will be called at the appropriate time.
The values inside the function will be in scope, so there’s no need to pass them (which wouldn’t help because the even delegation won’t pass them anyway). It’s called lexical scoping, or static scoping, or functional scoping (these terms aren’t identical, but they’re similar enough in this context).