Jump to content

AJAX XML Loading


radish

Recommended Posts

Hey all I'm having a lot of trouble with loading DOM elements on an HTML5 page using AJAX to load DOM elements from an XML document.Here's my code

// GLOBAL VARIABLES	var XML_DOC;//function checkReadyState(obj) {	if(obj.readyState == 4) {		return true;	}	return false;}function loadPage(pageName) {	// TESTING TO GET XML CONTENT	$("div#main").append( $(XML_DOC).find("page#" + pageName).clone(true).children() );}$(document).ready(function(){	var request;	// FIREFOX, OPERA, CHROME, IE7+	if(window.XMLHttpRequest) { request = new XMLHttpRequest(); }		// IE5, IE6	else if(window.ActiveXObject) {		request = new ActiveXObject("MSXML2.XMLHTTP");	}		// FETCHING XML FILE	request.open("GET", "./content.xml", true);	request.send();	XML_DOC = request.responseXML.documentElement;		loadPage("about");		console.log('Page Loaded (OnLoad)');});

I want the browser to load the xml into a global variable that can be accessed later when the user wants to click a link and load up a new page however the xml never loads until after the page is finished loading.The only way I can get the XML_DOC variable to not end up null is by inserting this

alert("request");

for some reason when I tell the browser to set up an alert on the request variable it forces the browser to load the XML file. and then finishes the rest of the script.please note that the xml won't load in any browser. but in firefox in the firebug console it shows that the xml has loaded and is giving code 304 not modified.**also firebug is giving me this errorrequest.responseXML is null(?)()main.js (line 30)resolveWith(context=Document #, args=[function()])jquery-1.6.1.js (line 995)ready(wait=undefined)jquery-1.6.1.js (line 428)DOMContentLoaded()jquery-1.6.1.js (line 901)[break On This Error] XML_DOC = request.responseXML.documentElement;

Link to comment
Share on other sites

When you write alert("request"); you're not outputting the request variable, you're just printing the word "request"The reason that it works when you use alert() is because you're making it delay long enough to load the file. What you really should be doing is to wait for the event indicating that the XML file has been loaded.

	// FETCHING XML FILE	request.onreadystatechange = fileLoaded;	request.open("GET", "./content.xml", true);	request.send();	function fileLoaded() {	  if(request.readyState == 4) {		XML_DOC = request.responseXML.documentElement;		loadPage("about");		console.log('Page Loaded (OnLoad)');	  }	}

Link to comment
Share on other sites

sorry I didnt mean to write alert("XML_DOC"); i meant to write it without quotes.thanks though you helped me figure out why if(request.readyState ==4) wasn't working

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...