First page Back Continue Last page Image

Reading Server Data

<?xml version="1.0"?>

<choices xml:lang="EN">

<item><label>Alabama</label><value>AL</value></item>

<item><label>Alaska</label><value>AK</value></item>

<item><label>Arizona</label><value>AZ</value></item>

<item><label>Arkansas</label><value>AR</value></item>

<item><label>California</label><value>CA</value></item>

<item><label>Colorado</label><value>CO</value></item>

<!DOCTYPE html>

<html>

<head>

<title>My First Ajax Script</title>

<script src="script01.js"></script>

</head>

<body>

<p>

<a id="makeTextRequest" href="gAddress.txt">Request a text file</a><br>

<a id="makeXMLRequest" href="us-states.xml">Request an XML file</a>

</p>

<div id="updateArea"> </div>

</body>

</html>

window.addEventListener("load",initAll,false);

var xhr = false;

function initAll() {

document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);

document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);

}

function getNewFile(evt) {

makeRequest(this.href);

evt.preventDefault();

}

function makeRequest(url) {

if (window.XMLHttpRequest) {

xhr = new XMLHttpRequest();

}

else {

if (window.ActiveXObject) {

try {

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

catch (e) {

}

}

}

if (xhr) {

xhr.addEventListener("readystatechange",showContents,false);

xhr.open("GET", url, true);

xhr.send(null);

}

else {

document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";

}

}

function showContents() {

if (xhr.readyState == 4) {

if (xhr.status == 200) {

if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {

var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);

}

else {

var outMsg = xhr.responseText;

}

}

else {

var outMsg = "There was a problem with the request " + xhr.status;

}

document.getElementById("updateArea").innerHTML = outMsg;

}

function getText(inVal) {

if (inVal.textContent) {

return inVal.textContent;

}

return inVal.text;

}

}

3 Parts:

1) Create xhr (XmlHttpRequest)

2) Evaluate xhr

3) Output xhr's data (outMsg)

readyState Values

0

Uninitialized

1

Open & Loading

2

Headers Loaded

3

Loading & Useable

4

Complete

us-states.xml

From XMLHttpRequest Object Events list