jquery 可排序保存到数据库无法正常工作

jquery sortable saving to database not working properly

我正在尝试将 jquery 可排序功能合并到我的网站中,但在数据库中保存位置让我头疼不已......我已经为此奋斗了 3 天,而且我似乎无法正常工作。

就目前而言,它正在将头寸保存到数据库中,但不是按照您期望的顺序或头寸。意思是,如果我将位置 0 中的项目移动到位置 1,它会以不同的顺序在数据库中保存这些位置。查看实时版本 here.

这是我的代码...

index.php 文件:

<div id="container">
   <?php
      require_once 'conn.php';
      $q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
      $result = mysqli_query($db, $q);
      if ($result->num_rows > 0) {
         while($items = $result->fetch_assoc()) {
      ?>
      <div id='sort_<?php echo$items['position'] ?>' class='items'>
         <span>&#9776;</span> <?php echo$items['description'] ?>
      </div>
      <?php
         }
      }
   ?>
</div>

js.js 文件:

$("#container").sortable({
   opacity: 0.325,
   tolerance: 'pointer',
   cursor: 'move',
   update: function(event, ui) {
      var itId = 3;
      var post = $(this).sortable('serialize');

      $.ajax({
         type: 'POST',
         url: 'save.php',
         data: {positions: post, id: itId },
         dataType: 'json',
         cache: false,
         success: function(output) {
            // console.log('success -> ' + output);
         },
         error: function(output) {
            // console.log('fail -> ' + output);
         }
      });

   }
});
$("#container").disableSelection();

save.php 文件:

require_once('conn.php');

$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);

$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);

foreach($arr['sort'] as $a) {
   $row = $result->fetch_assoc();
   $sql = " UPDATE items
            SET position = '$a'
            WHERE id = '{$row['id']}' ";
   mysqli_query($db, $sql);
}

echo json_encode( ($arr['sort']) );

谁能指出我在这方面哪里出错了?

提前致谢。

谢尔盖

像这样更改您的 JS 代码:

{...}
   tolerance: 'pointer',
   cursor: 'move',
// new LINE
   items: '.items', // <---- this is the new line
   update: function(event, ui) {
      var itId = 3;
      var post = $(this).sortable('serialize'); // it could be removed
// new LINES start
      var post={},count=0;
      $(this).children('.items').each(function(){
       post[++count]=$(this).attr('id');
      });
// new LINES end
      $.ajax({
{...}

通过这个 $.each 循环,您可以覆盖您的 var post -> serialize 并定义您自己的排序顺序。现在看看你的 $_POST["positions"] 和 PHP print_r($_POST["positions"]); 并且你有你自己的位置。

万一有人登陆这里,这就是我的情况...

注意: 我没有在 index.php select 函数中创建准备好的语句。但你可能应该。

index.php 文件:

<div id="container">
      <?php
         require_once 'conn.php';
         $q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
            $result = mysqli_query($db, $q);

         if ($result->num_rows > 0) {

            while( $items = $result->fetch_assoc() ){
      ?>
               <div id='sort_<?php echo $items['id'] ?>' class='items'>
                  <span>&#9776;</span> <?php echo $items['description'] ?>
               </div>
      <?php
            }
         }
      ?>
   </div>

jquery 可排序文件:

var ul_sortable = $('#container');

   ul_sortable.sortable({
      opacity: 0.325,
      tolerance: 'pointer',
      cursor: 'move',
      update: function(event, ui) {
         var post = ul_sortable.sortable('serialize');

         $.ajax({
            type: 'POST',
            url: 'save.php',
            data: post,
            dataType: 'json',
            cache: false,
            success: function(output) {
               console.log('success -> ' + output);
            },
            error: function(output) {
               console.log('fail -> ' + output);
            }
         });

      }
   });
   ul_sortable.disableSelection();

更新php文件:

$isNum = false;

foreach( $_POST['sort'] as $key => $value ) {
    if ( ctype_digit($value) ) {
        $isNum = true;
    } else {
        $isNum = false;
    }
}

if( isset($_POST) && $isNum == true ){
    require_once('conn.php');
   $orderArr = $_POST['sort'];
    $order = 0;
    if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
        foreach ( $orderArr as $item) {
            $stmt->bind_param("ii", $order, $item);
            $stmt->execute();
            $order++;
        }
        $stmt->close();
    }
    echo json_encode(  $orderArr );
    $db->close();
}