簡體   English   中英

無法使用javascript解析本地xml文件

[英]Not able to parse local xml file with javascript

當我嘗試使用簡單的javascript解析本地xml文件時,xhr.open之后的代碼未得到執行。

<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

請幫忙。

最好將本地文件視為禁區。 安全限制很高。 而是在localhost上運行Web服務器,並使用它訪問您的頁面。

您可以嘗試使用本地Web服務器來快速解決問題。

無需在localhost上設置Web服務器。...只需下載aptana studi o軟件並在其中導入您的項目...並運行html文件,aptana直接打開瀏覽器並自動創建名稱為http://127.0.0.1的 Web服務器。 :8000 /您的項目名稱

之后,您將不會收到任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM