我使用ajax读取xml文件,xmlhttp.responseText能取得正确的xml内容,但是xmlhttp.responseXML.documentElement为空。
1. 环境:windows7+IE9, html里调用ajax操作本地xml文件.不需要把这个html发布到web服务器上。测试在firefox成功但在ie8和9失败!!!
2. ajax如下:
- JScript code
function getXmlHttpPrefix() { if (getXmlHttpPrefix.prefix) return getXmlHttpPrefix.prefix; var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"]; var o; for (var i = 0; i < prefixes.length; i++) { try { // try to create the objects o = new ActiveXObject(prefixes[i] + ".XmlHttp"); return getXmlHttpPrefix.prefix = prefixes[i]; } catch (ex) {}; } throw new Error("Could not find an installed XML parser");}//////////////////////////// Start the Real stuff ////////////////////////////// XmlHttp factoryfunction XmlHttp() {}XmlHttp.create = function () { try { if (window.ActiveXObject) { return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp"); } else if (window.XMLHttpRequest) { var req = new XMLHttpRequest(); //some versions of Moz do not support the readyState property //and the onreadystate event so we patch it! if (req.readyState == null) { req.readyState = 1; req.addEventListener("load", function () { req.readyState = 4; if (typeof req.onreadystatechange == "function") req.onreadystatechange(); }, false); } return req; } } catch (ex) { throw new Error("Your browser does not support XmlHttp objects"); }}function _startLoadXmlTree(url) { var xmlHttp = XmlHttp.create(); if (xmlHttp.overrideMimeType){ xmlHttp.overrideMimeType("text/xml; charset=UTF-8"); } xmlHttp.open("GET", sSrc, true); // async xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4) { alert(xmlHttp.responseText); //可以取得xml的内容????????????? alert(xmlhttp.responseXML.documentElement); //为空??????????? } }; // call in new thread to allow ui to update window.setTimeout(function () { xmlHttp.send(null); }, 10);}
3. xml 如下:
- XML code
<?xml version="1.0" encoding="UTF-8"?><tree><tree text="MH" src="GuideList/MH.xml"/><tree text="MR" src="GuideList/MR.xml"/><tree text="a.swf" action="JavaScript:Play('player?file=file:///D:/Test/Guides/Flash/a.swf')"/><tree text="cc.swf" action="JavaScript:Play('player?file=file:///D:/Test/Guides/Flash/cc.swf')"/><tree text="movie_name.swf" action="JavaScript:Play('player?file=file:///D:/Test/Guides/Flash/movie_name.swf')"/></tree>
问题:
请问这是怎么回事?ajax在IE8 IE9都不能正常工作,但是在firefox就没问题。
------解决方案--------------------------------------------------------
在服务器端
response.setContentType("text/xml;charset=UTF-8");这句的位置,应该是在最开始,即创建这个response的