Reputation: 826
I'm trying to test if the xml file have the tag "<group>
"
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", "xmlfile.xml", false);
xmlhttp.send(null);
xml = xmlhttp.responseXML.documentElement;
var thegroup = xml.getElementsByTagName('group')[0];
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
Even if my xml file have the tag "<group>
" the result is always negative, and the variable "thegroup
" is undefined.
"xml
" give me "[object Element]"
Where is my mistake?
PS: I'm only interested in webkit, I don't care about IE, Opera or Firefox for now.
EDIT : HERE IS MY ACTUAL CODE
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=UTF-8">
<title>xmltest</title>
<script type="text/javascript">
function init() {
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", "xmlfile.xml");
xmlhttp.send(null);
xmlhttp.onreadystatechange = callbackFunction;
function callbackFunction(){
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseXML.documentElement;
var group = xml.getElementsByTagName('group')[0];
console.debug(xml)
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
}
}
};
</script>
</head>
<body onLoad="init();">
</body>
</html>
and my xmlfile.xml :
<?xml version="1.0" ?>
<group type="vertical">
<name>name</name>
<title>title</title>
</group>
At this point the alert is triggered saying :
No <group>
in the XML: [object Element]
So maybe my problem is just on the way I try to find the <group>
tag ?
Upvotes: 3
Views: 23358
Reputation: 11598
XMLHttpRequest is asynchronous, it doesn't work that way. When you use xmlhttp.send(null);
you have to define callback function that will be executed when the server responds with the data, otherwise you are trying to access empty data.
The code would look something like this:
var xmlhttp = new window.XMLHttpRequest();
xmlhttp.open("GET", "xmlfile.xml");
xmlhttp.send(null);
xmlhttp.onreadystatechange = callbackFunction;
function callbackFunction(){
if (xmlhttp.readyState == 4){
xml = xmlhttp.responseXML.documentElement;
var thegroup = xml.getElementsByTagName('group')[0];
if (!group) {
alert('No <group> in the XML: ' + xml);
return;
} else {
alert(xml + 'have a <group> tag');
}
}
}
this way, you are using onReadyStateChange
to tell the browser to run callbackFunction
everytime the server sends back a response. It tests for the readyState
to be 4 which means that the request has been completely served.
Upvotes: 8
Reputation: 385174
var thegroup = xml.getElementsByTagName('group')[0]; if (!group) { alert('No <group> in the XML: ' + xml); return; } else { alert(xml + 'have a <group> tag'); }
What is group
? Did you mean thegroup
?
Upvotes: 1