views:

34

answers:

1

I am working on a page that uses javascript / AJAX to parse xml from a file. I need to be able to parse a url on the loading of a page and insert it into a div. I have the script written but I need help getting 2 things: 1) having it parse an XML file and load that data into a div on page load 2) the option to click a link and load that data into the same div instead of what was there when the page loaded.

I am using an external script to do this & embeded a link to it in my page

HTML example to request data:

<div id="rightcolumn">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>

How do I change that to load #1 when the page loads & #2 when a link is clicked?

For the script, do I need anything special at the top to make sure it loads properly? jQuery has $(document).ready(function() {//GUTS}, do I need something similar with AJAX?

My Script

function loadXMLDoc(url){
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function(){

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

    var anno= xmlhttp.responseXML.documentElement.getElementsByTagName("anno");
    // Parser Guts

 }
document.getElementById('rightcolumn').innerHTML=txt;
  }
}
  xmlhttp.open("GET","url",true);
  xmlhttp.send();
A: 

Usage

<!-- when the user clicks -->
<button onclick="ajax('#ELEMENT','cd_catalog.xml')">Get CD info</button>

// when the page loads
window.onload = function () {
  ajax('#ELEMENT', 'cd_catalog.xml');
};

or you can place a script tag at the bottom of the page, or use the dom ready event

Code

function getXmlHttpObject() {
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    if (!xmlHttp) {
        alert("Your browser does not support AJAX!");
    }
    return xmlHttp;
}

function ajax(el, url, onSuccess, onError) {
    if (typeof el == "string")
      el = document.getElementById(el);
    var xmlHttp = getXmlHttpObject();
    xmlHttp.onreadystatechange = function() {
        if (this.readyState === 4) {
            // onSuccess
            if (this.status === 200 ) {
              if (el)
                 el.innerHTML = this.responseText;
              if (typeof onSuccess == 'function')
                onSuccess(this.responseText);
            }
            // onError
            else if(typeof onError == 'function') {
                onError();
            }
        }
    };
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
    return xmlHttp;
}​
galambalazs