我的程序中有一个 4 列表,其中一列是每行都有一个删除按钮的列。每当我单击删除按钮时,我希望它删除相应的行并通过 AJAX 发送删除查询来删除数据库中的该行。
现在似乎发生的是每当我单击删除按钮时,它都会删除其上面的行,或者如果我删除上面没有行的顶行,它根本不会删除,我就是这样做的不想。
我的控制台中没有收到任何错误。尽管如此,我每次都会收到成功的行已删除
消息。
那么我该如何解决这个问题并让删除工作,以便删除与按钮所在位置对应的行?
带有删除按钮的表格 HTML:
<table id="skuTable" cellspacing="5" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th class="skuRow">SKU Group</th>
<th class="skuRow">Group ID</th>
<th class="skuRow">Edit</th>
<th class="skuRow">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($query) as $row) {?>
<tr>
<td class="sku_group" id="sku_group-<?php echo intval ($row['SKU Group'])?>"><?php echo $row['SKU Group'];?></td>
<td class="group_id" align="center" id="group_id-<?php echo intval ($row['Group_ID'])?>"><?php echo $row['Group_ID'];?></td>
<td><button type="button" class="edit" name="edit">Edit</button></td>
<td><button type="button" class="delete" onclick="deleteRow(this)">Delete</button></td>
</tr>
<?php } ?>
</tbody>
JavaScript:
function deleteRow(r) {
if (confirm('Are you sure you want to delete this entry?')) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("skuTable").deleteRow(i);
}
request = $.ajax({
type: "POST",
url: "delete.php",
data: "Group_ID="+i
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row deleted");
} else {
console.log("row failed to delete");
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
删除.php:
<?php
$SKU_Group = $_POST['SKU Group'];
$Group_ID = $_POST['Group_ID'];
$host="xxxxxxxxxx";
$dbName="xxxxxx";
$dbUser="xxxxxxxxxxxx";
$dbPass="xxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$delete = "DELETE FROM SKU_Group_Dim WHERE Group_ID = '$Group_ID'";
$stmt = $pdo->prepare($delete);
$result = $stmt->execute();
echo json_encode($result);
if(!$result) {
echo sqlsrv_errors();
}
?>
最佳答案
问题是表头的 rowIndex 为零,而实际行则从 rowIndex 1 开始。例如
request = $.ajax({
type: "POST",
url: "delete.php",
data: "Group_ID="+i+1
});
编辑答案,因为我读问题的速度太快。
关于javascript - 单击按钮时删除正确的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42306530/