PHP 新手入門之AJAX 與 MYSQL
下面的實例將示範網(wǎng)頁如何透過AJAX 從資料庫讀取資訊:
首先我們要在資料庫中建立一張表格
如下圖所示:
#然後我們寫一個html的頁面,程式碼如下:
<!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","demo.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>
這段程式碼要交給demo.php來處理
註:showUser()函數(shù)會執(zhí)行下列步驟:
檢查是否有使用者被選擇
建立XMLHttpRequest 物件
建立在伺服器回應(yīng)就緒時執(zhí)行的函數(shù)
#向伺服器上的文件發(fā)送請求
請注意添加到URL 末端的參數(shù)(q)(包含下拉列表的內(nèi)容)
下面我們寫上一個deno.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 user WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysqli_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>"; mysqli_close($con); ?>
解釋:當(dāng)查詢從JavaScript 傳送到PHP 檔案時,將會發(fā)生:
#1.?PHP 開啟一個到MySQL 資料庫的連線
2.?找到選取的使用者
3.?建立HTML 表格,填入數(shù)據(jù),並發(fā)回"txtHint" 佔位符
?注:本段程式碼需要大家自己複製到自己的伺服器上,然後去運行,看看什麼樣的一個效果
????????數(shù)據(jù)庫必須要去建立
????????