gpt4 book ai didi

javascript - 取消选中复选框时 AJAX 不起作用

转载 作者:行者123 更新时间:2023-11-29 17:56:39 25 4
gpt4 key购买 nike

每次选中或取消选中该复选框时,我都试图更改我在 db 上的标志值。但出于某种原因,只有当我将我的复选框从 checked -> unchecked 更改时,ajax 才会触发。

HTML

    <table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Lot ID </th>
<th>Lot Name </th>
<th>Block Located </th>
<th>Status </th>
<th>Action </th>
</tr>
</thead>
<tbody>
<?php
$sql = $db->prepare("SELECT * from tbl_lot
LEFT JOIN tbl_block ON tbl_lot.blockID = tbl_block.blockID
WHERE lotStatus <> 2");

$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC))
{
$id = $result['lotID'];
$lotName = $result['lotName'];
$status = ($result['lotStatus']==1) ? "checked" : "";
$blockName = $result['blockName'];
$blockID = $result['blockID'];

echo "
<tr>
<td>$id</td>
<td>$lotName</td>
<td>$blockName</td>
<td>
<input type='checkbox' onchange='switchStatus($id,$status)' data-toggle='toggle' $status>
</td>
<td>
<div class='btn-group' role='group'>
<input type='button' value='Manage' onclick='Xmanage($id,$blockID,\"$lotName\")' class='btn btn-info'>
<input type='button' value='Remove' onclick='Xdelete($id)' class='btn btn-danger'>
</div>
</td>
</tr>
";
}
?>
<tbody>
</table>

这是我的 AJAX 代码:

    function switchStatus(id,status){
var theID = id;
var theStatus = status;
if(theStatus==1){
$.ajax({
url: "ajax/updateProjectStatus.php",
type: "POST",
data: {
projectID : theID,
status : theStatus
},
cache: false,
success: function (data){
alert(data);
}
});
}
}

updateProjectStatus.php

 <?php
include "../../connection/connection.php";
$id = $_POST['projectID'];
$prevStats = $_POST['status'];
if($prevStats==1){$status = 1;}else{$status=0;}
$sql = "UPDATE tbl_project set projectStatus = '$status' WHERE projectID = '$id'";
$query = $db->prepare($sql);
$results = $query->execute();

?>

最佳答案

您必须更改以下代码。

HTML

<input type='checkbox' onchange='switchStatus($id, this)' data-toggle='toggle' $status>

AJAX 代码

function switchStatus(id,status){
var theID = id;
var theStatus = $(status).prop('checked');
if(theStatus){
theStatus = 1;
} else {
theStatus = 0;
}
$.ajax({
url : "ajax/updateProjectStatus.php",
type : "POST",
data : {
projectID : theID,
status : theStatus
},
cache : false,
success : function (data){
alert(data);
}
});
}

updateProjectStatus.php

<?php
include "../../connection/connection.php";
$id = $_POST['projectID'];
$status = $_POST['status'];
$sql = "UPDATE tbl_project set projectStatus = '$status' WHERE projectID = '$id'";
$query = $db->prepare($sql);
$results = $query->execute();
?>

关于javascript - 取消选中复选框时 AJAX 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com