I'm not sure, but I suppose the problem is that due to "Ajax" in Internet Explorer 6, 7 and 8 (the latter two if used in quirks-mode ) use ActiveX instead of% w / o itself, you should do the correct "ActiveX" check, in case you have XMLHttpRequest
and Microsoft.XMLHTTP
.
A very important detail is that you should always use XHR in Msxml2.XMLHTTP
pages, ie using http://
may fail.
So if you want to give some support for IE6 and 7/8 use this:
function XHR() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
} else if (window.ActiveXObject) {
try {
return new window.ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
return false;
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e1) {
return false;
}
}
}
A detail that in modern browsers does not affect, but in some of the old ones it was the problem with the order of the methods call, so I always used the following orderm, file:///
, .open
(or directly .onreadystatechange
) and .readyState
.
The use of the code would be something like (read about .send
):
var foo = XHR();
foo.open("GET", "/url", true); //Usa chama assíncrona
//Use o readyState após o .open, como já dito
foo.onreadystatechange = function() {
switch (foo.readyState) {
case 0:
//(não inicializado)
break;
case 1:
//(carregando)
break;
case 2:
//(já carregado)
break;
case 3:
//(interativo)
break;
case 4:
//(completo) ... Neste ponto já se pode chamar o responseText
alert(foo.responseText);
break;
}
};
//Faz a requisição
foo.send(null);
An example with other Activex (I've developed a lot for IEs and the previous code worked since IE5.01 +):
function XHR() {
if (window.XMLHttpRequest) {
return new window.XMLHttpRequest;
}
var XMLHttpFactories = [
"Msxml3.XMLHTTP", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"
];
var obj = false, i = 0, j = XMLHttpFactories.length;
for (; i < j; i++) {
try {
obj = new window.ActiveXObject(XMLHttpFactories[i]);
} catch (e) {
continue;
}
break;
}
return obj;
}
Note: The .readyState
is expendable, I only used it to avoid conflicts with variables in other scopes, which may be almost impossible but is only to avoid.
A tip, you'd rather avoid (never use) sync mode:
foo.open("GET", "/url", false);