我正在使用 javascript 读取 XML 文件,然后将其显示在我的 html 页面中
它在 FireFox 上完美运行。
我用谷歌搜索,发现这是因为我的文件位于硬盘本地,这就是 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();
}
最佳答案
如果您只想直接从磁盘运行它,您将无法像 Chrome 一样使用 ajax,并且其他浏览器可能不允许加载 file:///
url。
您可以通过使用文件输入或拖放操作来获取文件来解决此问题
HTML
Select the clocks.xml file
<input type="file" id="xmlfile">
Javascript
var fileInput = document.querySelector("#xmlfile");
fileInput.addEventListener("change",function(e){
var file = fileInput.files[0];
var reader = new FileReader();
reader.onloadend = function(){
var data = reader.result;
//data will now contain the xml text
//use DOMParser to parse it
var xmlDocument = (new DOMParser()).parseFromString(data,"application/xml");
//then use the various element methods to get the elements you need
//for instance if you had a <clock> element
var clockData = xmlDocument.querySelector("clock").textContent
};
reader.readAsText(file);
})
否则,您需要设置 cors 或从服务器加载 html 和 xml。
关于javascript - 在 javascript 中从本地主机访问 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52359333/