无法从xml标记中获取属性值
Unable to get attribute value from xml tag
我是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);
相关文章:
- 无法获取属性'selectedIndex'的未定义引用或null引用
- 如何从选择框中的选项中获取属性值
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- 使用Undercore获取属性值数组
- Microsoft JScript运行时错误:无法获取属性'的值;样式':对象为null或未定义
- "无法获取属性'的值;style'"当试图在IE中更改样式时
- 无法获取属性'字符串'的未定义或null引用IE 11 ASP.NET
- 无法获取属性'的值;拆分'在IE8中调用ajax之后
- JQuery关键字“;这个“;未获取属性值
- SCRIPT5007:无法获取属性'长度'的未定义引用或null引用
- 为什么我得到“;无法获取属性的值'SetReturnValue'"当使用ceebox显示YouT
- 无法获取属性'setActionableButtonState'的未定义引用或null引用
- JavaScript |对象:获取属性忍者移动
- 如何使用 jQuery 在循环中获取属性的值
- 无法获取属性'偏移'的未定义引用或null引用
- 从列表中的选定项获取属性值
- 获取属性(邮政编码)并在Google地图API 3中使用
- IE:无法获取属性'的值;clientWidth':对象为null或未定义
- 如何通过类名和过滤函数获取属性值
- 无法使用javascript表示法获取属性值