我正在尝试使用xml和javascript。在Firefox中,它使用XMLHttpRequest工作得很好但在IE(6-8)中我收到错误:
Object doesn't support this action
我正在使用以下功能:
function createRequestObject(){
var request;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
return request;
}
然后用:
调用它 var xhttp = createRequestObject();
xhttp.open("GET","myfile.xml",false);
...
有什么想法吗?
答案 0 :(得分:2)
尝试为请求var request
指定一个局部变量(虽然看起来不应该解决它)。
我会将这个fn用于轻量级XHR:
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08 **
** Code licensed under Creative Commons Attribution-ShareAlike License **
** http://creativecommons.org/licenses/by-sa/2.0/ **/
function XHConn()
{
var xmlhttp, bComplete = false;
try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlhttp = new XMLHttpRequest(); }
catch (e) { xmlhttp = false; }}}
if (!xmlhttp) return null;
this.connect = function(sURL, sMethod, sVars, fnDone)
{
if (!xmlhttp) return false;
bComplete = false;
sMethod = sMethod.toUpperCase();
try {
if (sMethod == "GET")
{
xmlhttp.open(sMethod, sURL+"?"+sVars, true);
sVars = "";
}
else
{
xmlhttp.open(sMethod, sURL, true);
xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
xmlhttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && !bComplete)
{
bComplete = true;
fnDone(xmlhttp);
}};
xmlhttp.send(sVars);
}
catch(z) { return false; }
return true;
};
return this;
}
用法:
var myConn = new XHConn();
if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
var fnWhenDone = function (oXML) { alert(oXML.responseText); };
myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);
答案 1 :(得分:0)
我认为您需要在请求前加上var
:
function createRequestObject(){
var request;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
return request;
}
IE经常遇到全局变量问题。