首页 > 解决方案 > 如何将 javascript 数组传递给 php 脚本

问题描述

我有一个普通的 html 表,里面装满了数据库条目。我有一个插件可以在此表中选择多行。现在我想单击一个按钮并删除数据库条目,所以我需要从数组中取出 id,但它在我的 php 脚本中。但我真的不知道该怎么做。

</div>


   <table id="myTable" class="content-table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Artikelnummer</th>
        <th>Name</th>
        <th>Preis</th>
      </tr>
    </thead>
    <tbody>
        <?php
          $sql = "SELECT * FROM artikel;";
          $result = mysqli_query($conn, $sql);
          $resultCheck = mysqli_num_rows($result);

          if ($resultCheck > 0) {
              while ($row = mysqli_fetch_assoc($result)) {

                ?> 
                <tr>
                <td> <?php echo $row["id"]?></td> <?php 
                ?> <td> <?php echo $row["artikelnummer"]?></td> <?php 
                ?> <td> <?php echo $row["name"]?></td> <?php 
                ?> <td> <?php echo $row["preis"]?> €&lt;/td> </tr><?php 
              }
          }

         ?>

    </tbody>
  </table> 
  </div>
var $rows = [];
    $(function() {
        console.log( "ready!" );
        // start plugin
        $('#myTable').TableSelection({
                sort : true, // sort or not (true | false)
                status : 'multiple', // single or multiple selection (default is 'single')
            }, function(obj){ // callback function return selected rows array
                $rows = obj.rows;
        });

    });
<?php
    include_once 'dbh.inc.php';

    $artid = ???;

    $sql = "DELETE FROM artikel WHERE id= $artid;";

    mysqli_query($conn, $sql);

    header("Location: ../index.php?daten=success");

标签: javascriptphphtmlarrays

解决方案


您可以使用 html 属性来执行此操作。我用 html、css 和 javascript 为你做了一个例子。

这是你的html。

<table id="tableSelected" class="content-table">
    <thead>
      <tr>
        <th>ID</th>
        <th>Artikelnummer</th>
        <th>Name</th>
        <th>Preis</th>
      </tr>
    </thead>
    <tbody>
      <tr data-id="1">
        <td>1</td>
        <td>1-1</td>
        <td>Test</td>
        <td>1</td>
      </tr>
      <tr data-id="2">
        <td>2</td>
        <td>2-1</td>
        <td>Foo</td>
        <td>1</td>
      </tr>
  </tbody>
</table>

如您所见,每个“tr”标签都有“data-id”属性。


var $rows = [];
    $(function() {
      $('#tableSelected').TableSelection({
        sort : true,
        status : 'multiple',
      }, function(obj) {
        $.each(obj.rows, function(i, row){
          var id = $('#tableSelected').RowValue(row).attr('data-id') // You can get id with this code
        });
      });
    });

注意:https ://codepen.io/yusufilkeroguz/pen/vqPgzZ你可以从这里看到实时预览 :)


推荐阅读