Jump to content

Recommended Posts

I have several different pages that all need access to the same XML data file. I'm trying to use this fairly-standard function to load the file when the page loads. If I call getXMLFile() from within each pageLoadFunction, it works, but I'd like to use it to set up some other vars and avoid duplicating code.

getXMLFile = function(callback) {
	var request = new XMLHttpRequest();
	request.open("GET", "MyFileName.xml");
	request.setRequestHeader("Content-Type", "text/xml");
	request.onreadystatechange = function() {
	if (request.readyState == 4 && request.status == 200) {
		callback(request.responseXML);
        //Does code needed for all pages go here? Or where?
    	}
    };
	request.send();
}

What I would like to do is put something like this in my HTML, using a callback to call the fill function after the file has loaded:

<body onload="openXML(fillPageFunction)">	<!--There is a unique fill function for each page-->

OpenXML() would call getXMLFile() to load the data, then make use of it.

Procedurally, here is what I want to happen:

  1. Use getXMLFile() to load the data file
  2. Go ahead and render page HTML/CSS while file is loading
  3. When file is loaded, use it to fill some global vars needed on all pages
  4. Call a fill function to fill fields on the specific page

I've spent hours studying manuals, tutorials, and examples on using callbacks, but my procedural brain still can't make them work. Can someone familiar with callbacks please show me how I could accomplish this? (Using named functions, rather than anonymous, would probably help to make it clearer to me.)

  • To fill vars needed on all pages, would I put that code right after the line "callback(request.responseXML);"? Or where?
  • To fill fields on specific page I would call a unique fillPage function for each page. Where would I do that? Can I make that function a param to openXML()?

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...