HTML 結構
<li><input type="checkbox" name="uid" value="1" />用戶1</li>
<li><input type="checkbox" name="uid" value="2" />用戶2</li>
<li><input type="checkbox" name="uid" value="3" />用戶3</li>
<li><input type="checkbox" name="uid" value="4" />用戶4</li>
jQuery 代碼
var mt4Ids = [];
$('input[name=uid]').each(function() {
if (this.checked) {
mt4Ids.push($(this).val());
}
});
var data = { mt4Ids: JSON.stringify(mt4Ids) };
var pUrl = "/a/manageUser.html";
$.post(pUrl, data, function(response) {
if (response.state == 1) {
alert(response.msg);
location.href = "/h/permission.html";
} else {
alert("操作失敗");
}
}, 'json');
PHP 處理代碼
$mt4Ids = !empty($_POST['mt4Ids']) ? $_POST['mt4Ids'] : false;
if ($mt4Ids) {
// 移除 JSON 陣列括號與引號
$strip = preg_replace('/[\"\[\]]/', '', $mt4Ids);
$ids = explode(',', $strip);
foreach ($ids as $uid) {
permission_relation::add($uid, $gid); // $gid 為權限組 ID
}
echo json_encode(['state' => 1, 'msg' => '操作成功']);
} else {
echo json_encode(['state' => 0, 'msg' => '未選擇任何項目']);
}
return false;
關鍵點總結
- 前端收集:
.each() 遍歷 + this.checked 判斷 + .val() 取值
- 序列化:
JSON.stringify() 將陣列轉為字串傳輸
- 後端解析:
preg_replace 移除 []"" + explode(',') 還原陣列
- 回應格式:統一
{state, msg} 結構,前端據此判斷成功/失敗
安全建議
- PHP 端驗證
$uid 為合法整數:if (!ctype_digit($uid)) continue;
- 使用 Prepared Statement 防 SQL 注入
- 加入 CSRF Token 驗證