在我的数据库中,我的归档状态是布尔类型,
谢谢我已经连接到数据库
if (!$result = mysqli_query($con,"SELECT * FROM cursos"))
{
die("Error: " . mysqli_error($con));
}
并用复选框显示该字段的状态,
<?php if($row['status'] == 1) {
echo "<td>"."<input type = 'checkbox' checked='checked' name ='complete' value= '1'/>"."</td>";
}else
{
echo "<td>"."<input type = 'checkbox' name ='incomplete' value= '0'/>"."</td>";
}
?>
所以我需要做的是,一旦我选中或取消选中任何这些复选框,数据库字段就会自动取消,无需提交按钮。
好的,我确实按照您的建议编辑了我的代码,它现在可以工作了,这是新代码:
阿贾克斯代码
<script>
$(document).ready(function(e) {
$('.checkboxtest').change(function(){
if( $('.checkboxtest').prop('checked') )
{checkboxstatus = '1';}
else
{checkboxstatus = '0';}
$.ajax({
type: "POST",
url: "checkboxtestbackend.php",
data: {checkboxstatus: checkboxstatus},
})
.done(function(data, textStatus, jqXHR){alert(textStatus);})
.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
});//end ready
</script>
html代码是:
<?php if($row['status'] == 1) {
echo "<td>"."<input type = 'checkbox' class='checkboxtest' checked='checked' name ='complete' value= '1'/>"."</td>";
}else
{
echo "<td>"."<input type = 'checkbox' class='checkboxtest' name ='incomplete' value= '0'/>"."</td>";
}
?>
php后端代码是:
<?php
$checkboxstatus = $_POST['checkboxstatus'];
$host = "localhost";
$user = "username";
$password = "password";
$dbname = "name";
$cxn = mysqli_connect($host,$user,$password,$dbname);
if (mysqli_connect_errno()) {echo "No connection" . mysqli_connect_error();}
$query = " UPDATE cursos
SET status = '$checkboxstatus'
WHERE id = '12'";
$result = mysqli_query($cxn, $query) or die ("could not query database 1");
?>