0

我有一个 RegistrationResponseMessages.xml:

<messages>
  <error>
    <code id="501">Couldn't retrieve the HTML document because of server-configuration problems.</code>
    <code id="502">Server busy, site may have moved ,or you lost your dial-up Internet connection.</code>
  </error>
  <success></success>
</messages>

尝试使用 javascript 读取代码 id 501 和 502 的内容,但它不起作用。

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
        xmlhttp.send();
        xmlDoc = xmlhttp.responseXML;

        document.getElementById("errorCode403").innerHTML = getElementsByTagName(501)[0].childNodes[0].nodeValue);

在这里显示:

<label id="errorCode403" style="font-weight: 600; color: red;">give some error</label>

我的问题是什么?

4

1 回答 1

1

它是ajax,你必须等待数据返回,然后你必须以正确的方式访问它:

var xmlhttp;

if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onload = function() {
    var xmlDoc = this.responseXML,
        value  = xmlDoc.getElementsByTagName('501')[0].childNodes[0].nodeValue;
    document.getElementById("errorCode403").innerHTML = value;
}

xmlhttp.open("GET", "RegistrationResponseMessages.xml", false);
xmlhttp.send();

不确定 XML 中的遍历,因为501听起来像一个奇怪的 tagName ?

编辑:

要获取 ID 列表,您可以在 onload 处理程序中执行此操作:

xmlhttp.onload = function() {
    var xmlDoc = this.responseXML,

    var codes = xmlDoc.getElementsByTagName('code');
    var array = [];

    for (var i=0; i<codes.length; i++) {  
        array.push( codes[i].id );
    }

    console.log(array);
}
于 2013-07-18T06:40:19.147 回答