的JavaScript
這是JavaScript代碼儲存在檔案中“ selectuser.js ” :
var xmlHttp
function showUser(str){ xmlHttp=GetXmlHttpObject()if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return }var url="getuser.php"url=url+"?q="+strurl=url+"&sid="+Math.random()xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)}
function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText } }
function GetXmlHttpObject(){var xmlHttp=null;try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { //Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } }return xmlHttp;}
例如解釋
該stateChanged ( )和GetXmlHttpObject職能是一樣的PHP的AJAX章建議,您可以去那裡解釋這些。
該showUser ( )函數
如果一個項目在下拉框中選擇執行的功能如下:
籲請GetXmlHttpObject函數建立一個XMLHTTP物件
界定了網址(檔)傳送給伺服器
添加一個參數( Q )的網址與內容的下拉框
添加一個隨機數字,以防止伺服器使用快取檔案
呼叫stateChanged改變時,就會觸發
開幕XMLHTTP物件與特定網址。
發送一個HTTP請求到伺服器
PHP頁面
該伺服器的頁面要求的JavaScript ,是一個簡單的PHP檔案名稱為“ getuser.php ” 。
該網頁是PHP寫成的,並使用一個MySQL資料庫。
該代碼運行一個SQL查詢的資料庫,並返回結果作為HTML表:
<?php$q=$_GET["q"];$con = mysql_connect('localhost', 'peter', 'abc123');if (!$con) { die('Could not connect: ' . mysql_error()); }mysql_select_db("ajax_demo", $con);$sql="SELECT * FROM user WHERE id = '".$q."'";$result = mysql_query($sql);echo "<table border='1'><tr><th>Firstname</th><th>Lastname</th><th>Age</th><th>Hometown</th><th>Job</th></tr>";while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; }echo "</table>";mysql_close($con);?>
好了我們的php+ajax就完成了.