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

时间:2011-01-27 15:52:29

标签: 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>

1 个答案:

答案 0 :(得分:1)

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