PHP 新手入門之AJAX與XML
接下來我們以案例來詳解:
<!DOCTYPE html> <html> <meta charset="utf-8"> <head> <script> function showUser(str){ if (str==""){ document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行代碼 xmlhttp=new XMLHttpRequest(); }else{ // IE6, IE5 瀏覽器執(zhí)行代碼 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","3_2.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <br> <div id="txtHint"><b>Person info will be listed here.</b></div> </body> </html>
接下來我們建立一個php 的文件,代碼如下:
<?php $q=$_GET["q"]; $xmlDoc = new DOMDocument(); $xmlDoc->load("cd_catalog.xml"); $x=$xmlDoc->getElementsByTagName('ARTIST'); for ($i=0; $i<=$x->length-1; $i++) { // 處理元素節(jié)點 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++) { // 處理元素節(jié)點 if ($cd->item($i)->nodeType==1) { echo("<b>" . $cd->item($i)->nodeName . ":</b> "); echo($cd->item($i)->childNodes->item(0)->nodeValue); echo("<br>"); } } ?>
當(dāng) CD 查詢從 JavaScript 發(fā)送到 PHP 頁面時,將發(fā)生:
1. PHP 創(chuàng)建 XML DOM 對象
2. 查找所有 <artist> 元素中與 JavaScript 所傳數(shù)據(jù)相匹配的名字
3. 輸出 album 的信息,并發(fā)送回 "txtHint" 占位符
注:本段代碼要大家復(fù)制到本地測試,前提是要有上一節(jié)我們所說的數(shù)據(jù)庫表