AJAX 可用来与 XML 文件进行交互式通信。
当用户在下拉列表中选择某张 CD 时,会执行名为 "showCD()" 的函数。该函数由 "onchange" 事件触发:
<html> |
<head> |
<script> |
function showCD(str) |
{ |
if (str=="") |
{ |
document.getElementById("txtHint").innerHTML=""; |
return; |
} |
if (window.XMLHttpRequest) |
{ |
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行 |
xmlhttp=new XMLHttpRequest(); |
} |
else |
{ |
// IE6, IE5 浏览器执行 |
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); |
} |
xmlhttp.onreadystatechange=function() |
{ |
if (xmlhttp.readyState==4 && xmlhttp.status==200) |
{ |
document.getElementById("txtHint").innerHTML=xmlhttp.responseText; |
} |
} |
xmlhttp.open("GET","getcd.php?q="+str,true); |
xmlhttp.send(); |
} |
</script> |
</head> |
<body> |
<form> |
Select a CD: |
<select name="cds" onchange="showCD(this.value)"> |
<option value="">Select a CD:</option> |
<option value="Bob Dylan">Bob Dylan</option> |
<option value="Bonnie Tyler">Bonnie Tyler</option> |
<option value="Dolly Parton">Dolly Parton</option> |
</select> |
</form> |
<div id="txtHint"><b>CD info will be listed here...</b></div> |
</body> |
</html> |
showCD() 函数会执行以下步骤:
上面这段通过 JavaScript 调用的服务器页面是名为 "getcd.php" 的 PHP 文件。
PHP 脚本加载 XML 文档,运行针对 XML 文件的查询,并以 HTML 返回结果:
<?xml version="1.0" encoding="ISO-8859-1"?> |
<CATALOG> |
<CD> |
<TITLE>Empire Burlesque</TITLE> |
<ARTIST>Bob Dylan</ARTIST> |
<COUNTRY>USA</COUNTRY> |
<COMPANY>Columbia</COMPANY> |
<PRICE>10.90</PRICE> |
<YEAR>1985</YEAR> |
</CD> |
<CD> |
<TITLE>Hide your heart</TITLE> |
<ARTIST>Bonnie Tyler</ARTIST> |
<COUNTRY>UK</COUNTRY> |
<COMPANY>CBS Records</COMPANY> |
<PRICE>9.90</PRICE> |
<YEAR>1988</YEAR> |
</CD> |
</CATALOG> |
<?php |
$q=$_GET["q"]; |
$xmlDoc = new DOMDocument(); |
$xmlDoc->load("cd_catalog.xml"); |
$x=$xmlDoc->getElementsByTagName('ARTIST'); |
for ($i=0; $i<=$x->length-1; $i++) |
{ |
// 处理元素节点 |
if ($x->item($i)->nodeType==1) |
{ |
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) |
{ |
$y=($x->item($i)->parentNode); |
} |
} |
} |
$cd=($y->childNodes); |
for ($i=0;$i<$cd->length;$i++) |
{ |
// 处理元素节点 |
if ($cd->item($i)->nodeType==1) |
{ |
echo("<b>" . $cd->item($i)->nodeName . ":</b> "); |
echo($cd->item($i)->childNodes->item(0)->nodeValue); |
echo("<br>"); |
} |
} |
?> |
当 CD 查询从 JavaScript 发送到 PHP 页面时,将发生: