我有这段代码,我想添加复选框根据从数据库获取的数字与PHP,当点击复选框更新数据库中的一个字段与JQuery,这为1复选框,但这不能更多的复选框,我的PHP循环不工作,我可以添加循环复选框,当用户点击任何复选框更新自己的数据库字段,任何人可以解决我的问题?
我的JQuery代码:
$(document).ready(function () {
$('#mycheckbox').change(function () {
var returnVal = ("Are " + "you sure?");
if (returnVal) {
postToServer($(this).prop("checked"));
} else {
$(this).prop("checked", !$(this).is(":checked"));
}
});
function postToServer(state) {
let value = (state) ? 1 : 0;
$.ajax({
type: 'POST',
url: 'checkbox.php',
data: {'value': +value},
success: function (response) {
//handle response
}
});
}
}
和我的PHP代码:
$sql1="SELECT * FROM `users` ";
$result1= mysqli_query($conn,$sql1);
$row1=mysqli_fetch_assoc($result1);
$lights=$row1["lights"];
for ($i=0; $i < $lights; $i++){
if ($row["value"]=='1'){
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" checked=\"checked\">";
} else {
echo "<input type=\"checkbox\" class=\"checkbox\" id=\"mycheckbox\" >";
}
}
发布于 2019-03-27 02:34:36
这将修复循环未运行的问题,并应打印出每个用户的复选框
$users= mysqli_query($conn, "SELECT * FROM user");
while($row = mysqli_fetch_assoc($users)) {
if ($row["value"]=='1'){
echo '<input type="checkbox" class="checkbox" id="mycheckbox-'.$row["id"].'" checked="checked">';
}else {
echo '<input type="checkbox" class="checkbox" id="mycheckbox-'.$row["id"].'" >';
}
}
将用户的id添加到每个复选框id中,以使每个复选框具有唯一的id。
发布于 2019-03-27 05:13:16
$(document).ready(function () {
$('.checkbox').change(function () {
var returnVal = confirm("Are you sure?");
if (returnVal == true) {
postToServer($(this).val());
} else {
$(this).prop("checked", !$(this).is(":checked"));
}
});
function postToServer(state) {
let value = state;
$.ajax({
type: 'POST',
url: 'checkbox.php',
data: {'value': value},
success: function (response) {
//handle response
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
代码:
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result) ){
?>
<input type="checkbox" class="checkbox" value="<?php echo $row["id"] ?>">
<?php
}
?>
https://stackoverflow.com/questions/55368067
复制