【发布时间】:2018-09-16 23:52:29
【问题描述】:
我正在使用 javascript 读取 XML 文件,然后将其显示在我的 html 页面中
它在 FireFox 上运行良好。
我google了一下,发现是因为我的文件在我的硬盘中是本地的,这就是为什么Chrome和IE不能工作,Chrome会出现这个错误
clocks.html:20 Failed to load file:///B:/Data/clocks.xml:
Cross origin requests are only supported for protocol schemes:
http, data, chrome, chrome-extension, https.
所以我创建了一个本地网站并将文件添加到那里
http://localhost/clocks.xml
我可以通过该链接访问该文件,但是当我将脚本中的 clocks.xml 替换为以页面结尾的 http://localhost/clocks.xml 时,即使在 FireFox 中也无法正常工作并从 FireFox 收到此错误
Cross-Origin Request Blocked: The Same Origin Policy disallows
reading the remote resource at http://localhost/clocks.xml.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More]
我怎样才能让它在所有浏览器中都能正常工作
我的脚本在这里
window.onload = function() {
getClockInformation();
}
function getClockInformation() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
updateClocks(this);
}
};
xhttp.open("GET", "http://localhost/clocks.xml", true);
xhttp.send();
}
【问题讨论】:
-
如何直接从磁盘加载 html 文件?即您的浏览器以
file:///some/path/to/file.html结束?您需要从同一域加载 html 文件,在您的情况下为http://localhost。或者设置您的服务器为您的 xml 文件发送适当的 cors 标头 -
文件clocks.xml与html页面在同一个文件夹中..
-
是的,但是您是从 localhost url 加载 html 页面,即
http://localhost/file.html -
不,我只是双击它打开的 html,像这样 B:\data\clocks.html
-
是的,这会导致它检查 CORS,因为
file:///url 被视为与http://localhost不同的域。从 localhost 加载它,就像你是 xml 文件一样,即http://localhost/file.html并且请求将起作用
标签: javascript google-chrome firefox