AJAX 核心概念
- 同步:表單提交 → 頁面空白等待 → 整頁重新載入。
- 非同步:JavaScript 在背景與伺服器交換資料 → 頁面不重載 → 局部更新。
- 核心物件:
XMLHttpRequest (XHR) 或現代 fetch API。
實作步驟
1. 前端頁面 index.html
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>AJAX Demo</title></head><body>
<form>
<label>城市: <input type="text" id="city" name="city" onchange="queryZip()"></label>
<label>郵遞區號: <input type="text" id="zipcode" name="zipcode" readonly></label>
</form>
<script>
function queryZip() {
const city = document.getElementById('city').value.trim();
if (!city) return;
const xhr = new XMLHttpRequest();
xhr.open('GET', 'getZipcode.php?city=' + encodeURIComponent(city), true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('zipcode').value = xhr.responseText;
}
};
xhr.send();
}
</script>
</body></html>
2. 後端處理 getZipcode.php
<?php
// 實際專案應查詢資料庫,此處模擬
$city = $_GET['city'] ?? '';
if ($city) {
// 模擬回傳:城市名 + 固定代碼
echo $city . '_010';
} else {
echo '參數缺失';
}
?>
進階優化方向
- 使用
fetch() + async/await 簡化邏輯。
- 回傳 JSON 格式,前端統一解析。
- 加入防抖,避免使用者連續輸入觸發過多請求。
- 伺服器端增加快取、限流、輸入驗證。