I am new to AJAX and XML.
I have the following XML:
<rsp stat="ok">
<auth>
<token>123-123</token>
<perms>read</perms>
<user nsid="id" username="user_name" fullname="Full Name"/>
</auth>
</rsp>
I have the following code:
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();
I am unable to get any attribute(nsid, username, fullname) of <user>
xml tag. How can I fix this?
There is a closing parentheses )
too much at the end of this line:
document.getElementById("dummy").innerHTML= x.getAttribute("username"));
Update these two lines:
document.getElementById("dummy").innerHTML= x.getAttribute("username"));
window.location.replace("path/info.php?username="+ x.getAttribute("username"));
To
document.getElementById("dummy").innerHTML= x[0].getAttribute("username");
window.location.replace("path/info.php?username="+ x[0].getAttribute("username"));
x
is now x[0]
because getElementsByTagName in xmlDoc.getElementsByTagName("user")
returns a HTMLCollection and you want the first item from this collection.
Try with:
$xml=simplexml_load_file("FileName.xml") or die("Error: Cannot create object");
$xml->user['nsid'];
$xml->user['username'];
$xml->user['fullname'];
You should use a library for ajax/xml processing in JavaScript. The most popular library is jQuery (which is really powerful, so take a look at it!).
An easy example using jQuery can look like: ( 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.