我正在尝试将XML文档加载到Javascript中,以便可以在网站上输出,但是当我加载XML文档时它是null,因此每次尝试从中读取时都会出现异常。这是我的代码:
网页上的代码
var xmlDoc;
loadXML();
function loadXML(){
xmlDoc = loadXMLDoc("http://www.tomrichardsonweb.co.uk/ABC/xml/pubs.xml");
}
function loadPub(){
if(xmlDoc != null){
document.getElementById('pub').innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
}else{
alert("null");
}
loadXMLDoc方法
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
XML文件
< ?xml version="1.0" encoding="UTF-8" ?>
<pub>
<name>Bay Horse</name>
<description>Situated at the foot of the stunning Pennine Range, amidst the breathtaking landscape of Rivington, you will find The Bay Horse Inn. With open fires, cosy corners and a warm friendly atmosphere, this family run inn really does have something for everyone.
The perfect place to relax with family and friends our well stocked bar offers the finest cask ales, refreshing lagers and ciders, quality wines and spirits and a wide selection of soft drinks, teas and coffees.
For diners our chalkboards boast classic pub food, all freshly prepared and cooked to order, alongside a great range of award winning "Pieminister" pies.
And for those visiting the area on business or pleasure, or just passing through on a wider journey, and looking for somewhere to rest their heads then our bed and breakfast rooms could be just the answer! Our friendly team (and our friendly regulars!) will try to make your stay as enjoyable as possible.</description>
<web>N/a</web>
<email>N/a</email>
<phone>N/a</phone>
<image></image>
</pub>
我经常得到xmlDoc = null。这有什么问题?
编辑:在Chrome中,在网络标签下,它表示已加载xml文档。我正在我的网站托管的服务器上测试所有这些,而不是从我的机器上测试。
答案 0 :(得分:0)
首先,您应该将所有内联脚本移动到js文件,以便代码易于管理,现在就像您的函数一样
function loadPub(i, xml){....}
function loadXMLHTTP(url, callbackfn, args) {//callbackfn:fn you need to load after xml loads, args:argument array to pass to the call back function
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("No browser support for XML-HTTP-request object")
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
args.push( xmlhttp.responseXML);
callbackfn.apply(this,args)
}
}
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
}
function loadXML(){
xmlDoc = loadXMLHTTP("xml/pubs.xml",loadPub,[0]);
}
loadXML();
在这个函数中,ajax请求等待从服务器加载xml,然后用args和xml调用你传入的函数