虽然现在文件传输的方式主流的是用JSON,但是最近工作中用到了XML的文件读取,这个问题折腾了好一会,记录一下成功突破的方法。
读取XML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<p>测试读取方法!</p>
<script>
function loadXML() {
console.log("正在读取");
var xmlDoc;
try { //IE浏览器
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
} catch (e) { //firefox,opera...火狐、欧朋等浏览器
xmlDoc = document.implementation.createDocument("", "", null);
}
try {
xmlDoc.asyc = false; //是否异步调用
xmlDoc.load("./equipment.xml"); //文件路径
} catch (e) { //chrome
var xmlhttp = new window.XMLHttpRequest();
//创建一个新的http请求,并指定此请求的方法、URL以及验证信息
xmlhttp.open("GET", "./equipment.xml", false);
xmlhttp.send(null);
if (xmlhttp.readyState == 4) {
xmlDoc = xmlhttp.responseXML.documentElement;
}
}
console.log("读取完成");
//console.log(xmlDoc);
return xmlDoc;
}
</script>
<script>
var xmlDoc = loadXML();//调用该方法即读取出来
//... do anything you want
}
</script>
</body>
</html>
XML文件
<?xml version="1.0" encoding="utf-8"?>
<equipmentstore>
<equipment>
<category>Web_server</category>
<id>00001</id>
<position_x>200</position_x>
<position_y>200</position_y>
<shape/>
<link>00002</link>
</equipment>
<equipment>
<category>router</category>
<id>00002</id>
<position_x>400</position_x>
<position_y>400</position_y>
<shape/>
<link>00001</link>
<link>00003</link>
</equipment>
<equipment>
<category>router</category>
<id>000003</id>
<position_x>600</position_x>
<position_y>200</position_y>
<shape/>
<link>00002</link>
</equipment>
</equipmentstore>
爬坑指南
如果使用Chrome浏览器的话,即使你把以上的代码如法炮制,你还是无法读取到XML文件,在调试控制台会报错:
svg.html:32 Failed to load file:///.../xx.xml: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load '.../xxx.xml'.
//反正就是死活读取不到
主要是因为Chrome浏览器的安全机制问题,并且使用到http请求,不允许读取本地XML文件,解决办法是将其运行在服务器端。我这里将其放在了Tomcat上去跑,即使用Tomcat运行静态文件。在Tomcat的webapp文件夹下新建一个test文件夹,把静态文件放在里面,然后运行Tomcat,浏览器访问 localhost:8080/test/xxx.html
cd Tomcat的文件路径/bin
./startup.sh //运行
./shutdown.sh //停止
网站与 个人博客 同步更新,欢迎点击
网友评论