Jump to content

Loading XML files


Fukushousha

Recommended Posts

Hello all,I wanted to read some data from XML files instead of having it all in html in my site. I made the xml file, and tried to load it via javascript.This was the javascript function:

//the function to load XML filesfunction loadXML(filename){	//Internet Explorer		try	{		xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 		xmlDoc.async="false"; 		xmlDoc.onreadystatechange=verify; 		xmlDoc.load(filename); 		xmlObj=xmlDoc.documentElement;		//xmlDoc.onload= readXML;	}	//Firefox, Opera	catch(e)	{		xmlDoc=document.implementation.createDocument("","",null);		xmlDoc.async="false";		xmlDoc.onreadystatechange=verify;		xmlDoc.load(filename); 		xmlObj=xmlDoc.documentElement; 		  //xmlDoc.onload= readXML;	}}

The verify function just check for code 4 in the ready state. I am testing the connection later in a script by using this :loadXML('plangs.xml');alert(xmlObj.xml);What bothers me is that it works in IE, but not for firefox ( presumably opera too, but I do nto have it installed in this pc). What am I doing wrong? Or is this not the way to load XML files? Thanks in advance!

Link to comment
Share on other sites

I would advocate the use of the XMLHttpRequestObject to load and read XML (or any type of) document via JS. People seem to have less problems with it and there is no loss (as far as I know) of functionality.

var xmlObj;function loadXML(filename){xmlObj = (XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");xmlObj.onreadystatechange = function() {alert("XML has loaded: " + xmlObj.responseXML);}xmlObj.open("GET", "plangs.xml");xmlObj.send(null);}

Link to comment
Share on other sites

Thanks for the input friend!Actually I thought that the xmlhttrequest object was to be used in more complext situations only.I guess I had that idea because I used it succesfully in a much more complex script concerning xml-php-js-sql, the whole package. But you were right :) .

function loadXML(filename){	xmlObj = CreateXmlHttpObj(xmlObj);		xmlObj.onreadystatechange = function() 			{				if(xmlObj.readyState==4) 				{					  xmlDoc = xmlObj.responseXML.documentElement;					alert("XML Document loaded");				}							}	xmlObj.open("GET", filename);	xmlObj.send(null);}

This way it works like a charm! So now I guess I better start coding the parser who will read the xml file and extract the data I need. Thanks again !

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...