简明现代魔法 -> Ajax技术 -> Ajax 获取 XML 内容
Ajax 获取 XML 内容
2010-03-12
前端调用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="ajax.js"></script>
<style type="text/css">
table{border-collapse:collapse;border-spacing:0;}
table td{border:1px solid #999; padding:8px; }
#txtHint{margin-top:15px;}
</style>
<title>无标题文档</title>
</head>
<body>
<form name="form1">
请选择公司:
<select name="seccom">
<option value="0">请选择</option>
<option value="1">Google</option>
<option value="2">腾讯</option>
<option value="3">网易</option>
</select>
</form>
<div id="txtHint">
<table id="txtinfo"><tr><td>信息显示框</td></tr></table>
</div>
</body>
<script type="text/javascript" src="showHint.js"></script>
</html>
ajax.js
var xmlHttp;
function ajaxRequest(url)
{
if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
else if(window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp.onreadystatechange = ajaxResponse;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function ajaxResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
ajaxCallback();
}
}
}
showHint.js
function ajaxCallback()
{
var names = xmlHttp.responseXML.getElementsByTagName("name");
var adrs = xmlHttp.responseXML.getElementsByTagName("adr");
var div = document.getElementById("txtHint");
var txttabel = document.getElementById("txtinfo");
div.removeChild(txttabel);
table = document.createElement("TABLE");
table.id = "txtinfo";
var i = document.form1.seccom.selectedIndex;
if(i==0)
{
div.appendChild(table);
return;
}
var j=i-1;
name=names[j].firstChild.nodeValue;
nametxt=document.createTextNode(name);
adr=adrs[j].firstChild.nodeValue;
adrtxt=document.createTextNode(adr);
tr=document.createElement("TR");
td1=document.createElement("TD");
td1.appendChild(nametxt);
tr.appendChild(td1);
td2=document.createElement("TD");
td2.appendChild(adrtxt);
tr.appendChild(td2);
table.appendChild(tr);
div.appendChild(table);
}
document.form1.seccom.onchange=function Ajaxstart()
{
ajaxRequest("company.xml");
}
company.xml
<?xml version="1.0" encoding="utf-8" ?> <companys> <name>Google</name> <adr>佩奇、布林</adr> <name>Tencent</name> <adr>马化腾</adr> <name>NetEasy</name> <adr>丁磊</adr> </companys>
