无法从xml标记中获取属性值

Unable to get attribute value from xml tag

本文关键字:获取 属性 xml      更新时间:2023-09-26

我是AJAX和XML的新手。

我有以下XML:

<rsp stat="ok">
<auth>
<token>123-123</token>
<perms>read</perms>
<user nsid="id" username="user_name" fullname="Full Name"/>
</auth>
</rsp>

我有以下代码:

 function readXML(xml)
    {
        var xmlDoc = xml.responseXML;
        var x = xmlDoc.getElementsByTagName("user");
        document.getElementById("dummy").innerHTML= x.getAttribute("username"));
window.location.replace("path/info.php?username="+ x.getAttribute("username"));
    }
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function()
    {
        if(xhttp.readyState==4 && xhttp.status==200)
        {
            readXML(xhttp)
        }
    }
    xhttp.open("GET", <?php echo ($url);?>, true);
    xhttp.send();

我无法获取<user> xml标记的任何属性(nsid、用户名、全名)。我该怎么解决这个问题?

此行末尾有一个太多的括号)

document.getElementById("dummy").innerHTML= x.getAttribute("username"));

更新这两行:

document.getElementById("dummy").innerHTML= x.getAttribute("username"));
window.location.replace("path/info.php?username="+ x.getAttribute("username"));

document.getElementById("dummy").innerHTML= x[0].getAttribute("username");
window.location.replace("path/info.php?username="+ x[0].getAttribute("username"));

x现在是x[0],因为xmlDoc.getElementsByTagName("user")中的getElementsByTagName返回一个HTMLCollection,并且您想要该集合中的第一个项。

尝试使用:

$xml=simplexml_load_file("FileName.xml") or die("Error: Cannot create object");
$xml->user['nsid'];
$xml->user['username'];
$xml->user['fullname'];

您应该在JavaScript中使用一个用于ajax/xml处理的库。最流行的库是jQuery(它真的很强大,所以看看它吧!)。

使用jQuery的一个简单示例如下:(sample-os-jsFiddle)

// Callback for processing the response from the server
var callback = function (data) { 
    var token = data.getElementsByTagName("token");
    var tokenValue = token[0].innerHTML;

    var user = data.getElementsByTagName("user");
    var usernameAttributeValue = user[0].getAttribute("username");
};
// Actually calls the server, ajax endpoint, and calls callback on response
$.ajax(ajaxEndpointUrl).done(callback);