我有一個應用程序,用戶可以檢查輸入複選框,並將該值發送到數據庫而不重新加載頁面;它所做的。但是,當我取消選中相同元素的隱藏類型時;其中包含值0,但未提交,相反,它仍會從複選框中提交值1。複選框沒有用AJAX和PHP代替true
輸入是動態創建的:
function build_something(it, src){
var something = it;
var htag = it+"-header";
var ctr = document.createElement('div');
ctr.setAttribute('class', 'interest_container');
var lbl = document.createElement('label');
lbl.setAttribute('for', something);
var img = document.createElement('img');
img.setAttribute('src', src);
var title = document.createElement('h2');
title.setAttribute('id', htag);
var inp_f =document.createElement('input');
inp_f.setAttribute('type', 'hidden');
inp_f.setAttribute('name', something);
inp_f.setAttribute('value', 0);
var inp = document.createElement('input');
inp.setAttribute('type', 'checkbox');
inp.setAttribute('id', something);
inp.setAttribute('name', something);
inp.setAttribute('value', 1);
lbl.appendChild(img);
ctr.appendChild(lbl);
ctr.appendChild(inp_f);
ctr.appendChild(inp);
ctr.appendChild(title);
var elem = document.getElementById('idk');
elem.appendChild(ctr);
document.getElementById(htag).innerHTML = it;
}
綁定最接近元件抓住輸入和onchange
後檢查元件:
$('#interests').on('change', 'input', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
async: true,
data: $(this).serialize(),
success: function (msg) {
console.log(msg);
}
});
})
storeData是通過some.php
調用的函數:
function storeData($form_data, $table_name, $cxn){
if(!is_array($form_data)){
return false;
exit();
}
$types = str_repeat("s", count($form_data));
$params = array();
$params[] = &$types;
$keys = array_keys($form_data);
$values = array_values($form_data);
for ($i = 0; $i < count($values); $i++) {
$params[] = &$values[$i];
}
$sql = "INSERT INTO $table_name (" . implode(',', $keys) . ") VALUES (" .
implode(',', array_fill(0, count($values), '?')) . ")
ON DUPLICATE KEY UPDATE ";
$updates = implode(',', array_map(function($col) {
return "$col = VALUES($col)";
}, $keys));
$sql .= $updates;
$stmt = mysqli_prepare($cxn, $sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
return mysqli_stmt_execute($stmt);
}
時我檢查它提交的輸入框價值並存儲它;然而,當我取消選中相同的元素時,它應該發送一個值0,但它不會。
編輯:我的問題是不同的,因爲其他解決方案建議下拉。我不要那個。
可能重複的[jQuery序列化不註冊複選框](https://stackoverflow.com/questions/3029870/jquery-serialize-does-not-register-checkboxes) –
也許這個問題的答案(https) ://stackoverflow.com/q/44314075/1575353)將被發現有趣 –