PHP - AJAX 與 MySQL
AJAX 可用來(lái)與數(shù)據(jù)庫(kù)進(jìn)行交互式通信。
AJAX 數(shù)據(jù)庫(kù)實(shí)例?
下面的實(shí)例將演示網(wǎng)頁(yè)如何通過(guò) AJAX 從數(shù)據(jù)庫(kù)讀取信息:
html頁(yè)面展示
實(shí)例解釋 - MySQL 數(shù)據(jù)庫(kù)
在上面的實(shí)例中,我們使用的數(shù)據(jù)庫(kù)表如下所示:
實(shí)例解釋 - HTML 頁(yè)面
當(dāng)用戶在上面的下拉列表中選擇某位用戶時(shí),會(huì)執(zhí)行名為 "showUser()" 的函數(shù)。該函數(shù)由 "onchange" 事件觸發(fā):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <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","getuser.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">John Doe</option> <option value="2">tom Mary</option> <option value="3">lijing liuqi</option> <option value="4">liu li</option> </select> </form> <br> <div id="txtHint"><b>數(shù)據(jù)庫(kù)信息展示在這</b></div> </body> </html>
showUser() 函數(shù)會(huì)執(zhí)行以下步驟:
· ? 檢查是否有用戶被選擇
· ? 創(chuàng)建 XMLHttpRequest 對(duì)象
· ? 創(chuàng)建在服務(wù)器響應(yīng)就緒時(shí)執(zhí)行的函數(shù)
· ? 向服務(wù)器上的文件發(fā)送請(qǐng)求
· ? 請(qǐng)注意添加到 URL 末端的參數(shù)(q)(包含下拉列表的內(nèi)容)
PHP 文件
上面這段通過(guò) JavaScript 調(diào)用的服務(wù)器頁(yè)面是名為 "database" 的 PHP 文件。
?database.php" 中的源代碼會(huì)運(yùn)行一次針對(duì) MySQL 數(shù)據(jù)庫(kù)的查詢(xún),然后在 HTML 表格中返回結(jié)果:
database.php 文件
<?php $q=$_GET["q"]; $con = mysqli_connect('localhost','root','root','test'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } //mysqli_select_db($con,"ajax_demo"); $sql="SELECT * FROM Myguests WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>firstname</th> <th>lastname</th> <th>email</th> <th>Age</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['firstname'] . "</td>"; echo "<td>" . $row['lastname'] . "</td>"; echo "<td>" . $row['email'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; ; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>
解釋?zhuān)寒?dāng)查詢(xún)從 JavaScript 發(fā)送到 PHP 文件時(shí),將發(fā)生:
1.??? PHP 打開(kāi)一個(gè)到 MySQL 數(shù)據(jù)庫(kù)的連接
2.??? 找到選中的用戶
3.??? 創(chuàng)建 HTML 表格,填充數(shù)據(jù),并發(fā)送回 "txtHint" 占位符
程序成果展示: