I’m not sure, but I suppose the problem is that due to "Ajax" in Internet Explorer 6, 7 and 8 (these last two if used in quirks-mode) use Activex and not XMLHttpRequest
properly said it must make the Activex check "correct", in case it has the Microsoft.XMLHTTP
and the Msxml2.XMLHTTP
.
A very important detail is that you should always use XHR on pages http://
, or be used in file:///
can fail.
So if you want to give some support for IE6 and 7/8 use so:
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 ancient occurrences were the problem with the order of the methods call, so I always used the following orderm, .open
, .onreadystatechange
(or directly the .readyState
) and .send
.
The use of the code would be something like (read on the .readyState
):
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 (however I 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 window.
is dispensable, I only used it to avoid conflicts with variables in other scopes, which may be almost impossible, but it is only to avoid.
A tip, prefer to avoid (never use) Sync mode:
foo.open("GET", "/url", false);
ie6 ? man, what freedom...
– Caio Felipe Pereira
Could be that check of
me.done
, I don’t see this function being defined in your code.– bfavaretto
@bfavaretto In fact the
if
declared before those 2 or executes, thethis.readyState
isundefined
:( . He’s declared, but I put a/* ... */
.– Klaider
Will that
this
in IE is something else... It doesn’t hurt to try xhr.readyState...– bfavaretto
@bfavaretto Also not... I put
xhr
and nothing happened :/. Thethis
is the same asxhr
in the scope ofonreadystatechange
.– Klaider
Nicematt I know, should be, but in IE6, you never know ;-)
– bfavaretto