【问题标题】:Delete Table Row on Button Click Using Ajax使用 Ajax 单击按钮上的删除表行
【发布时间】:2017-02-13 20:29:48
【问题描述】:

我有一个包含 4 列的 HTML 表:SKU 组、Group_ID、编辑按钮和删除按钮。我现在正在处理删除功能,并且想要它,以便每当我按下删除按钮时,都会弹出一个确认框,然后如果按下“确定”,它会删除该行并发送一个删除查询,将其从数据库中删除。

我知道我要使用 Ajax 和一个单独的 PHP 脚本来进行删除查询,但似乎无法弄清楚。任何帮助表示赞赏!

删除按钮的 HTML:

<td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td>

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: 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="xxxxxx"; 
  $dbName="xxxxxx"; 
  $dbUser="xxxxxxxxxxxxxx"; 
  $dbPass="xxxxxxxxxxx";

  $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 json_encode(sqlsrv_errors());
  }

?>

【问题讨论】:

  • 这看起来你在正确的轨道上,什么不工作?
  • 从外观上看,您在 ajax 中的数据变量没有与您的 $_POST getter 对应的参数。
  • @LoveenDyall 是的,我知道这肯定是个问题,我只是不知道应该去那里
  • 无论您如何命名 $_POST 参数,您都应该对相同的参数字符串进行 url_encode。所以数据:“Group_ID=”+i;或类似的东西

标签: javascript php html ajax sql-delete


【解决方案1】:

JavaScript

首先,我注意到您正在使用 jQuery,那么为什么不尝试充分利用它呢?

首先为您的.delete 按钮创建一个onclick 事件处理程序。

$('.delete').click(function () {
    // do something when delete button is clicked
});

您只想在用户确认并且已成功从数据库中删除该行后删除该行。

if (confirm('Are you sure you want to delete this entry?')) {
    // shorter call for doing simple POST request
    $.post('delete.php', data, function (response) {
        // do something with response
    }, 'json');
    // ^ to indicate that the response will be of JSON format
}

但是应该将什么data 传递到$.post() 以便我们知道要删除哪条记录?嗯,可能是我们要删除的记录的 ID。

HTML

由于您没有发布太多的 HTML,假设您按如下方式构建表格:

<table class="skuTable">
    <tr>
        <td>123</td><!-- sku group -->
        <td>456</td><!-- group id -->
        <td><input type="button" class="edit" name="edit" value="Edit" ... ></td>
        <td><input type="button" class="delete" name="delete" value="Delete" onclick="deleteRow(this)"></td>
    </tr>
    <!-- more similar records -->
</table>

更改它,以便您可以轻松地找到和访问组的 ID,例如通过向您的单元格添加一个类。 (由于我们已经创建了一个onclick 处理程序,您不再需要为您的.delete 按钮使用onclick 属性。)

<table class="skuTable">
    <tr>
        <td class="skuGroup">123</td>
        <td class="groupId">456</td>
        <td><input type="button" class="edit" name="edit" value="Edit" ... ></td>
        <td><input type="button" class="delete" value="Delete"></td>
    </tr>
    <!-- more similar records -->
</table>

JavaScript(再次)

您可以通过使用 jQuery 遍历轻松找到关联的 ID。现在把所有东西放在一起:

$('.delete').click(function () {
    var button = $(this), 
        tr = button.closest('tr');
    // find the ID stored in the .groupId cell
    var id = tr.find('td.groupId').text();
    console.log('clicked button with id', id);

    // your PHP script expects GROUP_ID so we need to pass it one
    var data = { GROUP_ID: id };

    // ask confirmation
    if (confirm('Are you sure you want to delete this entry?')) {
        console.log('sending request');
        // delete record only once user has confirmed
        $.post('delete.php', data, function (res) {
            console.log('received response', res);
            // we want to delete the table row only we received a response back saying that it worked
            if (res.status) {
                console.log('deleting TR');
                tr.remove();
            }
        }, 'json');
    }
});

PHP

人们使用准备好的语句的原因之一是为了防止攻击。您尝试使用它很好,但您没有正确使用它(阅读 Jay 的评论)。 您希望将变量绑定到 SQL 中的参数。您可以通过在PDOStatement::execute() 函数中传递一个变量数组来做到这一点。

当您删除一条记录时,您可以通过使用PDOStatement::rowCount() 检查受影响的记录数来检查它是否有效。

我从来没有任何理由检查execute() 是否有效。

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

//$SKU_Group = $_POST['SKU Group'];

$Group_ID = $_POST['Group_ID'];

$host="xxxxxx"; 
$dbName="xxxxxx"; 
$dbUser="xxxxxxxxxxxxxx"; 
$dbPass="xxxxxxxxxxx";

$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);

$stmt = $pdo->prepare("DELETE FROM SKU_Group_Dim WHERE Group_ID = ?");
$stmt->execute(array($Group_ID));

// send back the number of records it affected
$status = $stmt->rowCount() > 0;

// send back a JSON 
echo json_encode(array('status' => $status));

// nothing else can be outputted after this
?>

当然,这还没有经过测试,因此可能存在一些错误。如果您打开浏览器的控制台日志,您可以按照日志查看发生了什么。

【讨论】:

  • 感谢您的回答。我的脚本中有代码并且在运行时,单击删除按钮时没有任何反应。知道为什么吗?
  • 我将 JS 的前两行编辑成这样,现在显示确认框...document.addEventListener('DOMContentLoaded', function () { document.getElementById("delete").addEventListener('click',function () { 但是,它现在告诉我收到的响应状态现在为 false跨度>
  • 正确遵循代码。您的每个 HTML 按钮都应该有一个 class 属性 not 一个 id 属性。这些按钮共享此类,因为它们共享相同的onclick 事件处理程序。 ID 仅用于一个元素,而不是多个元素。遵循控制台日志以确保您在每个断点处获得正确的值。如果响应状态为 false,请查看您传递给 AJAX 的内容。
  • 好的,我完全按照您的代码进行操作,但是当我单击删除按钮时没有任何反应,因此在日志或任何内容中都没有可查看的内容
  • 确保您已 (1) 包含 jQuery (2) 将您的 jQuery 代码包装在 $(function() { ... }); (3) 将 class="delete" 添加到您的删除按钮 (4) 从您的删除中删除 onclick 属性按钮。
猜你喜欢
  • 2018-11-09
  • 2021-09-05
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
相关资源
最近更新 更多