Reputation: 249
I am attempting to write this code so when I click on the XML button it will show my XML document. I am unable to get the button to do anything, I am assuming that the function is missing something. Any help would be appreciated. Thanks in advance.
Function
<script language = "JavaScript">
xmlOpen = function(){
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET","gameXML.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
}
</script>
Button HTML
<p>
<label>List of users:</label>
<input type="button" value="XML" id="users" onclick="xmlOpen()">
</p>
Upvotes: 0
Views: 3166
Reputation: 2593
Are you serving these files from a web server? OR are you just opening the HTML page from your file system? If you use Chrome and try to open the HTML file from your file system, you will get an error (see the console) when you click the "XML" button.
To get around this, you can either serve the files from a web server (even on your local machine) OR you could try opening the HTML page in Firefox.
In terms of displaying the contents of the XML file, try taking a look at this question: How do I loop through XML Nodes in JavaScript?
Update:
I was successful in testing with the code below. Opening the HTML file from my Desktop in Firefox.
gameXML.xml
<?xml version="1.0" encoding="UTF-8" ?>
<users>
<user>Bob</user>
<user>James</user>
<user>Karen</user>
<user>Tom</user>
<user>Linda</user>
</users>
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Test Page</title>
</head>
<body>
<p>
<label>List of users:</label>
<input type="button" value="XML" id="users" onclick="xmlOpen()">
<table id="tbody"></table>
</p>
<script language = "JavaScript">
xmlOpen = function(){
var users, i, len;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.open("GET", "gameXML.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
users = xmlDoc.getElementsByTagName("user");
len = users.length;
for (i = 0; i < len; i++) {
var user = users[i].firstChild.nodeValue;
var tr = document.createElement("tr");
var td = document.createElement("td");
var textNode = document.createTextNode(user);
td.appendChild(textNode);
tr.appendChild(td);
document.getElementById("tbody").appendChild(tr);
}
}
</script>
</body>
</html>
Screenshot of result:
Upvotes: 1
Reputation: 510
did you forget to display the data? If so, add this to your function:
document.getElementById('users').innerHTML = xmlDoc;
If that does not work, change responseXML to responseText.
If that does not work, try replacing
xmlhttp.open("GET","gameXML.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
with
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("users").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gameXML.xml",true);
xmlhttp.send();
Upvotes: 1