gpt4 book ai didi

javascript - 加载的 XML 文档为空 (Javascript)

转载 作者:行者123 更新时间:2023-11-28 09:42:20 24 4
gpt4 key购买 nike

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

最佳答案

首先,您应该将所有内联脚本移至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,然后使用参数和 xml 调用您传入的函数

关于javascript - 加载的 XML 文档为空 (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12227776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com