function loadXML(urlName){ var xmlDoc; try{ //IE xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); }catch(e){ //firefox,opera xmlDoc = document.implementation.createDocument("","",null); } try{ xmlDoc.asyc = false; //是否异步调用 xmlDoc.load(urlName); //文件路径 }catch(e){ //chrome var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET",urlName,false); //创建一个新的http请求,并指定此请求的方法、URL以及验证信息 xmlDoc = xmlhttp.responseXML; } return xmlDoc; } 我在外部封装了一个函数读取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> </head> <body> <p id="test"> </p> </body> <script src="./loadXMLDoc.js"></script> <script> var XMLtest = loadXML('./xml.xml'); console.log(XMLtest); </script> </html>
这是我的文件结构
慕粉3166282