tuna.html
Código:
<!DOCTYPE html>
<html>
<head>
<script type ="text/javascript" src ="tuna.js"></script>
</head>
<body onload="process()">
Here is a list of people...
<br/>
<br/>
<div id="theD"/>
</body>
</html>
tuna.xml
Código:
<?xml version ="1.0" encoding="UTF-8" standalone="yes" ?>
<response>
<people>
<person>
<name>
Antonio garcia
</name>
<ssn>
sdffggh4456678
</ssn>
<name>
Anid gutierrez
</name>
<ssn>
s34566776783785
</ssn>
</person>
</people>
</response>
tuna.js
Código:
var xmlHttp = createXmlHttpRequestObject();
//create object
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
//called onLoad
function process(){
if(xmlHttp){
try{
xmlHttp.open("GET", "tuna.xml" true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}catch(e){
alert(e.toString());
}
}
}
//when state changes
function handleStateChange(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
try{
handleResponse();
}catch(e){
alert(e.toString());
}
}else{
alert(xmlHttp.statusText);
}
}
}
// handle the reponse from the server
function handleResponse(){
var xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
names = root.getElementsByTagName("name");
ssns = root.getElementsByTagName("ssn");
var stuff = "";
for(var i=0; i < names.length; i++){
stuff = names.item(i).firstChild.data + " - " + ssns.item(i).firstChild.data + "<br/>";
}
theD = document.getElementById("theD");
theD.innerHTML = stuff;
}
El resultado debe ser mas o menos así:
Here is a list of people...
Antonio garcia - sdffggh4456678
Anid gutierrez - s34566776783785