AJAX 資料庫示例
AJAX 可用於與資料庫進行互動式通訊。
AJAX 資料庫示例
下面的示例將演示網頁如何使用 AJAX 從資料庫中獲取資訊。
示例說明 - showCustomer() 函式
當用戶在上面的下拉列表中選擇一個客戶時,將執行一個名為“showCustomer()”的函式。該函式由“onchange”事件觸發
showCustomer
function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
showCustomer() 函式執行以下操作:
- 檢查是否選擇了客戶
- 建立一個 XMLHttpRequest 物件
- 建立伺服器響應準備好時要執行的函式
- 將請求傳送到伺服器上的檔案
- 請注意,一個引數 (q) 被新增到了 URL 中(其值為下拉列表的內容)。
AJAX 伺服器頁面
由上面 JavaScript 呼叫伺服器上的頁面是一個 PHP 檔案,名為“getcustomer.php”。
“getcustomer.php”中的原始碼針對資料庫執行查詢,並將結果顯示在 HTML 表中
<?php
$mysqli = new mysqli("伺服器名", "使用者名稱", "密碼", "資料庫名");
if($mysqli->connect_error) {
exit('無法連線');
}
$sql = "SELECT customerid, companyname, contactname, address, city, postalcode, country
FROM customers WHERE customerid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>