簡體   English   中英

使用JavaScript解析XML文件

[英]Using JavaScript to parse an XML file

我是Stack OverFlow和編碼的新手。 我正在嘗試獲取XML文件並使用JavaScript在瀏覽器中呈現它。 我查看了一些如何執行此操作的示例代碼,並提出了以下代碼:

<!DOCTYPE html>
<html>
<body>

<script>
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET","social.xml",false);
  xmlhttp.send();
  xmlDoc=xmlhttp.responseXML; 

document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
  { 
  document.write("<tr><td>");
  document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
  document.write("</td><td>");
  document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
  document.write("</td></tr>");
  }
  document.write("</table>");
</script>

</body>
</html>

無論如何,當我在本地服務器上運行它時,我試圖在表中顯示的數據都不會出現。 我的.html文件和.xml文件在同一個文件夾中,所以我相信我有正確的文件路徑。 我可能只是在這里犯了一個菜鳥錯誤,但我不能為我的生活弄清楚為什么沒有創建列出c_id和facebook_id值的表。 我四處尋找答案,但卻找不到任何答案。 任何幫助將不勝感激。 謝謝!

在發送請求之前,您需要向xmlhttprequest添加onload事件偵聽器。 此外,您可能需要使用DOMParser解析XML。 無論如何,這應該適用於現代瀏覽器:

<!DOCTYPE html>
<html>
    <body>

        <script>
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }



            xmlhttp.onload = function() {
                var xmlDoc = new DOMParser().parseFromString(xmlhttp.responseText,'text/xml');

                console.log(xmlDoc);

                document.write("<table border='1'>");
                var x=xmlDoc.getElementsByTagName("CD");
                for (i=0;i<x.length;i++)
                { 
                    document.write("<tr><td>");
                    document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
                    document.write("</td><td>");
                    document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
                    document.write("</td></tr>");
                }
                document.write("</table>");

            }


            xmlhttp.open("GET","social.xml",false);
            xmlhttp.send();
            </script>

    </body>
</html>

現在,只有幾件值得一提的關於你正在做的事情:

  • xmlhttprequest對象有許多不同的參數,意味着各種各樣的東西: readystate ,status code,works。 您可能會從中獲益更多。

  • 永遠不應該使用document.write 事實上,任何HTML注入方式都應該非常謹慎地處理。 您可以使用許多MVC-esque框架中常見的基於模板的解決方案,如果您願意,可以使用我的 :)

暫無
暫無

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

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