AJAX 資料庫示例
AJAX 可用於與資料庫進行互動式通訊。
AJAX 資料庫示例
下面的示例將演示網頁如何使用 AJAX 從資料庫中獲取資訊。
示例說明 - showCustomer() 函式
當用戶在上面的下拉列表中選擇客戶時,一個名為 showCustomer()
的函式會被執行。該函式由 onchange
事件觸發
showCustomer
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xhttp.open("GET", "getcustomer.php?q="+str);
xhttp.send();
}
the showCustomer()
function does the following
- 檢查是否選擇了客戶
- 建立一個 XMLHttpRequest 物件
- 建立伺服器響應準備好時要執行的函式
- 將請求傳送到伺服器上的檔案
- 請注意,一個引數 (q) 被新增到了 URL 中(其值為下拉列表的內容)。
AJAX 伺服器頁面
由上面的 JavaScript 呼叫,伺服器上的頁面是一個名為 "getcustomer.php" 的 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>";
?>