我在Chrome中阅读以下XML文档时遇到了问题 - 似乎没有任何问题,但它在Firefox中运行得非常好。这是浏览器兼容性问题吗?
<html>
<head>
<title>XML</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript'>
function XMLload(){
jQuery.post(url,function(data){getxml(data);},'xml');
}
function dataFromTag(node,t){
var d=node.getElementsByTagName(t);
if(d.length==0)
return('');
return(d[0].firstChild.nodeValue);
}
jQuery(document).ready(function(){XMLload();});
// all the code above this line can be re-used without change
// all the code below will need altering for a different document and different structure
var url='cohort.xml';
var xmlcohort;
function getxml(xmldoc){
xmlcohort = xmldoc.getElementsByTagName('student');
var hstr = '<html><head><title></title></head><body>';
hstr += '<p>Cohort:</p><form>';
hstr += '<select size="' + xmlcohort.length + '" onclick="parent.student_info(this.selectedIndex);">';
for( var i = 0; i < xmlcohort.length; i++ ) {
hstr += '<option>' + dataFromTag(xmlcohort[i], 'name') + '</option>';
}
hstr += '</select></form></body></html>';
with( document.getElementById('cohort').contentDocument ) {
open();
write(hstr);
close();
}
}
function student_info(idx) {
var hstr = '<html><head><title></title></head><body><dl>';
hstr += '<dt>Name</dt><dd>' + dataFromTag(xmlcohort[idx], 'name') + '</dd>';
hstr += '<dt>Module</dt><dd>' + dataFromTag(xmlcohort[idx], 'module') + '</dd>';
hstr += '<dt>Mark</dt><dd>' + dataFromTag(xmlcohort[idx], 'mark') + '</dd>';
hstr += '</dl></body></html>';
with( document.getElementById('student').contentDocument ) {
open();
write(hstr);
close();
}
}
</script>
</head>
<body>
<iframe id='cohort' height='300' width='200'></iframe>
<iframe id='student' height='300' width='200'></iframe>
<p>Here is the <a href="cohort.xml">xml data</a></p>
</body>
</html>
以下是cohort.xml的内容:
<cohort>
<student>
<name>Bob</name>
<module>COA122</module>
<mark>72</mark>
</student>
<student>
<name>Alice</name>
<module>COB250</module>
<mark>84</mark>
</student>
<student>
<name>Kate</name>
<module>COP180</module>
<mark>99</mark>
</student>
</cohort>
当我从硬盘驱动器运行时出现此错误。整个页面都没有加载 - 它只在我把它放在Web服务器上时才有效:
XMLHttpRequest cannot load file:///C:/Users/methuselah/Desktop/cohort/cohort.xml. Origin null is not allowed by Access-Control-Allow-Origin.
答案 0 :(得分:1)
这是Chrome中的一个已知问题:http://code.google.com/p/chromium/issues/detail?id=40787
如果这仅用于测试和开发,则可以使用Chrome命令行标记来解决此问题:--allow-file-access-from-files
。我刚测试了它,它让你的网页在Chrome中本地工作。
Windows:chrome.exe --allow-file-access-from-files
Mac:/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files
Linux:Linux用户不需要有关如何通过命令行工作的说明! ; - )