利用 jQuery 的 $.ajax() 或 $.post() 方法,前端將表單數據序列化為 JSON 發送至 PHP 後端,後端處理後返回 JSON 響應,前端解析渲染頁面,實現無刷新數據交互。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON 交互演示</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
</head>
<body>
<div id="result">等待提交...</div>
<form id="myForm">
<p><label>姓名:</label> <input type="text" name="username" required></p>
<p><label>年齡:</label> <input type="number" name="age" required></p>
<p><label>工作:</label> <input type="text" name="job" required></p>
</form>
<button id="sendBtn">提交數據</button>
<script>
$(function() {
$("#sendBtn").click(function() {
// 方法一:serialize() 序列化表單
var formData = $("#myForm").serialize();
$.ajax({
url: 'process.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(response) {
var html = "姓名:" + response.username +
" | 年齡:" + response.age +
" | 工作:" + response.job;
$("#result").html(html);
},
error: function(xhr) {
$("#result").html("請求失敗:" + xhr.statusText);
}
});
});
});
</script>
</body>
</html>
<?php
header("Content-Type: application/json; charset=utf-8");
// 接收 POST 數據
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$age = isset($_POST['age']) ? intval($_POST['age']) : 0;
$job = isset($_POST['job']) ? trim($_POST['job']) : '';
// 構建響應數組
$response = [
'username' => $username,
'age' => $age,
'job' => $job
];
// 輸出 JSON
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
$.post('process.php', {
username: $("input[name='username']").val(),
age: $("input[name='age']").val(),
job: $("input[name='job']").val()
}, function(data) {
// data 已自動解析為對象(需確保 dataType: 'json' 或服務端正確設置 Header)
$("#result").html("姓名:" + data.username + " | 年齡:" + data.age + " | 工作:" + data.job);
}, 'json');
error 回調提升用戶體驗此模式廣泛應用於:表單驗證、數據分頁加載、即時搜索建議、購物車操作、用戶註冊檢查等前後端分離交互場景。