javascript - 在 javascript 中从 localhost 访问 XML 文件
问题描述
我正在使用 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();
}
解决方案
如果您只想直接从磁盘运行它,您将无法将 ajax 用作 Chrome,并且可能其他浏览器只是不允许加载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 - 从字符串中提取分隔的数字组
- python - 由于缺少 dateutil 模块,crontab 未执行 python 文件
- bash - 在 sed 命令中使用双引号和变量
- python - 基于用户输入的查询,返回结果,然后使用新的用户输入运行查询
- firebase - 有没有办法使用 Firebase Auth 将验证电子邮件发送到自定义电子邮件 ID(比如管理员)而不是用户的电子邮件 ID?
- c - 如何在编译时为我的结构动态创建枚举
- javascript - 在 javascript onevent 函数中使用 this
- regex - 如何在 SparkNLP 中使用 RegexMatcher
- python - Python更好的断点方式?
- vb.net - VB中的If语句问题