測試代碼如下:
xml.xml 一個(gè)簡單的xml文件
<?xml version="1.0" encoding="gb2312"?>
<data>abc</data>
test.htm: 一個(gè)簡單的使用xmlhttprequest獲取xml資源的頁面:
<html>
<head>
<script type="text/JavaScript">
<!--
document.domain="emu.emu.com"
var newsXML;
function init(){
newsXML = window.XMLHttpRequest?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));//選擇合適的xmlhttprequest控件
newsXML.onreadystatechange= handleXML;
newsXML.open("GET","xml.xml",true);
newsXML.send(null);
}
function handleXML(){
if(newsXML.readyState==4){
alert(newsXML.responseText)
try{
alert(newsXML.responseXML.getElementsByTagName("data").length)
}catch(e){
alert(e)
}
}
}
//-->
</script>
</head>
<body onload="init()">
測試firefox的bug
</body>
</html>
注意這一行:
document.domain="emu.emu.com"
配置WINDOWS\system32\drivers\etc\hosts:
127.0.0.1 localhost
127.0.0.1 emu.emu.com
好了,開啟apache把上面的xml和htm文件發(fā)布出去,通過emu.emu.com域名來訪問test.htm文件,結(jié)果報(bào)錯(cuò):
只要設(shè)置了domain,不管domain怎么設(shè),getElementsByTagName 都肯定報(bào)權(quán)限不足錯(cuò)誤。其實(shí)根本就沒有任何跨域操作,而且連responseText都可以獲得了,訪問getElementsByTagName 還有什么權(quán)限限制的必要?莫名其妙!
在IE下運(yùn)行就很正常。在firefox下把document.domain="emu.emu.com"這一行刪除后也運(yùn)行正常,因此確定是firefox的bug。
按照http://www.mozilla.org/projects/security/components/jssec.html 中的說明設(shè)置netscape.security.PrivilegeManager.enablePrivilege 來提升頁面訪問權(quán)限也無法解決此問題。
這個(gè)bug造成了合法的跨域xml請求(同一個(gè)父域)無法正確解析返回的xml數(shù)據(jù)(但是能訪問文本信息)。這不是逼我用AjaH嘛?