<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "http://www.rgraph.net/sample.xml";
xmlhttp.open("GET",url,false); //If url is replaced by the downloaded file named "sample.xml" this works and give the output of 1.
// but works only on Mozilla
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("stats");
alert(x.length);
</script>
</body>
</html>
Any comment or advice would be much appreciated!
PS: Why does this only work on Mozilla and NOT on Safari or Chrome?
Before using the content of a file accessed via AJAX request, you should check the properties of the request object (readyState and status). And you should use the event onreadystatechange for that.
And the DOM reference of the document of an XML file is a distinct object: documentElement
A basic example:
Code:
<script type="text/javascript">
var xmlhttp;
function AJAX(url){
xmlhttp=null;
// Modern browsers
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.url=url;
xmlhttp.onreadystatechange=xmlhttpResponse;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
// old IE
else if (window.ActiveXObject)
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
if (xmlhttp)
{
xmlhttp.url=url;
xmlhttp.onreadystatechange=xmlhttpResponse;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
}
function xmlhttpResponse()
{
// if loaded
if (xmlhttp.readyState==4)
{
// if status is "OK"
if (xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML.documentElement;
var x=xmlDoc.getElementsByTagName("stats");
alert(x.length);
}
else
{
alert("The connection failed or the file does not exist!")
}
}
}
onload=function(){
AJAX('sample.xml');
}
</script>
Bookmarks