Javascript 代码不会打开 XML 文件并放入表中

标签 javascript xml file

我知道这可能是一个愚蠢的问题,但对于这个应用程序,我无法弄清楚为什么代码不会打开 XML 文件并将其放入表中。有什么问题吗?

<script type ="text/javascript">



function displayData() {

var xmlEl =docObj.getElementsByTagName("books");
var table = document.createElement("table");

table.border = "1";
var tbody = document.createElement("tbody");

//Append body to table
table.appendChild(tbody);
var row = document.createElement("tr");

for(colHead=0; colHead < xmlEl[0].childNodes.length; colHead++){
if(xmlEl[0].childNodes[colHead].nodeType !== 1){
continue;
}
var tableHead = document.createElement("th");
var colName = document.createTextNode(xmlEL[0].childNodes[colHead].nodeName);
tableHead.appendChild(colName);
row.appendChild(tableHead);
}

//Append the row to the body
tbody.appendChild(row);

// Create table row
for(i=0; i < xmlEl.length; i++){
    row = document.createElement("tr");
    // Create the row/td elements
    for(j=0; j <xmlEl[i].childNodes.length; j++){
        //Skip it if the type is not 1
        if(xmlEl[i].childNodes[j].nodeType !== 1){
        continue;
    }

//Insert the actual text/data from the XML document
var td =document.createElement("td");
var xmlData =
    document.createTextNode(xmlEl[i].childNodes[j].firstChild.nodeValue);
    td.appendChild(xmlData);
    row.appendChild(td);
}
tbody.appendChild(row);
}

document.getElementById("xmldata").appendChild(table);

}

function getXML() {
    if(typeof document.implementation.createDocument !== "undefined"){
    docObj = document.implementation.createDocument("","", null);
    docObj.onload = displayData;

}
else if (window.ActiveXObject) {
    docObj = new ActiveXObject("Microsoft.XMLDOM");
    docObj.onreadystatechange = function () {
        if(docObj.readyState === 4) displayData()
    };
    }
    docObj.load("books.xml");
}

<?xml version="1.0"?>
<books>
<book>
    <title>MySQL Bible</title>
    <author>Steve Sueshring</author>
    <isbn>978764549328</isbn>
    <publisher>Wiley Publishing, Inc.</publisher>
</book>
<book>
    <title>Javascript Step By Step</title>
    <author>Steve Sueshring</author>
    <isbn>978735624498</isbn>
    <publisher>Microsoft Press</publisher>
</book>
</books>

最佳答案

看起来您在客户端浏览器上运行脚本,在这种情况下您无权访问文件系统,很可能您会收到“访问被拒绝”异常

关于Javascript 代码不会打开 XML 文件并放入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4818562/

相关文章:

javascript - 为什么我的代码告诉我 .draw 不是函数?

c# - 为什么在除 IE 之外的所有浏览器上 XMLHttpRequest.status == 0?

javascript - JS promise : error handling concept

xml - 使用自定义拆分方法的 Camel 拆分器

python - 在 Python 中复制多个文件

javascript - 使用 setTimeout 引导进度条进度

java - 如何为通话功能创建确认对话框

xml - 如何使用xslt比较和合并两个xml

c++ - mprotect 和文件句柄

c - 使用 C 替换文本文件中的行