1

我正在尝试将 XML 文档加载到 Javascript 中,以便可以将其输出到网站上,但是当我加载 XML 文档时它为空,因此每次尝试从中读取时都会出现异常。这是我的代码:

网页上的代码

    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 文档。我在我的网站托管的服务器上测试所有这些,而不是在我的机器上。

4

1 回答 1

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 传入的函数

于 2012-09-07T11:31:59.067 回答