當我嘗試使用簡單的javascript解析本地xml文件時,xhr.open後面的代碼沒有得到執行。無法使用javascript解析本地xml文件
<html>
<head>
<script type="text/javascript">
function createXMLHttpRequestObject()
{
if (window.XMLHttpRequest) {
xhttp=new XMLHttpRequest();
} else {
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xhttp;
}
function makeRequest()
{
var xhr = createXMLHttpRequestObject();
try {
xhr.open("GET", 'books.xml', false);
xhr.send(null);
//xhr.onreadystatechange = function() {
//if(this.readyState == 4) {
xmlDoc=xhr.responseXML;
alert(xmlDoc);
//}
}
} catch(err) {
alert("ERROR: " + err.description);
}
}
</script>
</head>
<body>
<div onclick="makeRequest();">test<br></div>
<div id="out">Output Here</div>
</body>
</html>
books.xml文件如下,
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
當Internet我發現,搜索「出於安全原因,現代的瀏覽器不允許跨域訪問。」 http://www.w3schools.com/xml/xml_parser.asp
請幫忙。
感謝它現在的工作。 :) –
@PravinChikhale請接受回答並關閉此問題... –