<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Checkbox POST Demo</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<fieldset>
<legend>選擇項目</legend>
<label><input type="checkbox" class="checkbox" name="checkbox" value="1"> 選項 1</label>
<label><input type="checkbox" class="checkbox" name="checkbox" value="2"> 選項 2</label>
<label><input type="checkbox" class="checkbox" name="checkbox" value="3"> 選項 3</label>
<label><input type="checkbox" class="checkbox" name="checkbox" value="4"> 選項 4</label>
</fieldset>
<button class="but_delet_choice">提交選取項目</button>
<div id="result"></div>
<script>
$('.but_delet_choice').click(function() {
// 1. 取得所有被勾選的 checkbox
var $checked = $("input[name='checkbox']:checked");
if ($checked.length === 0) {
alert('請至少勾選一項!');
return;
}
// 2. 組裝資料結構:[[value, 固定值2], ...]
var payload = [];
$checked.each(function() {
payload.push([$(this).val(), 2]); // 陣列元素為 [值, 固定參數]
});
// 3. AJAX POST 提交
$.post('backend.php', { data: JSON.stringify(payload) })
.done(function(response) {
$('#result').html('' + response + '
');
})
.fail(function() {
alert('請求失敗');
});
});
</script>
</body>
</html>
<?php
header('Content-Type: text/plain; charset=utf-8');
if (isset($_POST['data'])) {
$json = $_POST['data'];
$arr = json_decode($json, true); // true = 關聯陣列
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON 解析錯誤: " . json_last_error_msg();
exit;
}
echo "收到資料結構:\n";
var_dump($arr);
// 實際業務邏輯...
// foreach ($arr as $item) { $val = $item[0]; $fixed = $item[1]; ... }
}
?>
// serializeArray() 自動處理所有表單欄位,checkbox 未勾選不會被包含
var formData = $('#myForm').serializeArray();
// 結果: [{name:"checkbox", value:"1"}, {name:"checkbox", value:"3"}, ...]
// 若需將同名 checkbox 合併為陣列
var combined = {};
$.each(formData, function(i, field) {
if (!combined[field.name]) combined[field.name] = [];
combined[field.name].push(field.value);
});
console.log(JSON.stringify(combined));
// {"checkbox":["1","3"], "username":["john"]}
| 問題 | 原因 | 解決 |
|---|---|---|
| 後端收到空字串 | 未勾選任何 checkbox,`:checked` 為空集合 | 前端檢查 `length > 0` 再送出 |
| PHP `$_POST['checkbox']` 只有一個值 | 同名表單欄位未加 `[]`,PHP 只取最後一個 | 名稱改為 `name="checkbox[]"` 或前端 JSON 打包 |
| 中文亂碼 | 編碼不一致 | 頁面 ``、PHP `header('Content-Type: ... charset=utf-8')`、DB 連線 `SET NAMES utf8mb4` |
此模式廣泛用於批次刪除、多選提交、權限勾選等場景,掌握「前端 JSON 打包 → 後端解析」流程是前後端分離開發的基礎技能。