遍历序列化的 sortable table

Looping through a serialized sortable table

我正在通过 AJAX 将一些序列化数据发送到 PHP 脚本:

HTML:

<table class="mytable">
    <tbody>
        <tr id="item_01">
            <td>content</td>
        </tr>
        <tr id="item_02">
            <td>content</td>
        </tr>
        <tr id="item_03">
            <td>content</td>
        </tr>
        <tr id="item_04">
            <td>content</td>
        </tr>
        <tr id="item_05">
            <td>content</td>
        </tr>
    </tbody>
</table>

JS:

$( '.mytable tbody' ).sortable({
    update: function() {
        items = $( this ).sortable( 'serialize' );
        $.ajax({
            url: 'ajax.php',
            type: 'post',
            data: { action: 'foo', items }
            cache: false,
            error: function() {
                console.log( 'Error' );
            }
        });
    }
});

PHP:

$action = $_POST['action'];
if ($action == 'foo') {
    $items = $_POST['items'];
    for ( $i = 0; $i < count($items); $i++ ) {
        .....
    }
}

我的印象是可以在不进行任何转换的情况下循环遍历 $_POST['items'] var,但我得到的是序列化数据:

item[]=val_1&item[]=val_2&item[]=val_3& ... &item[]=val_n

我怎样才能遍历这个?

提前致谢

所以问题在于您 post 调用 ajax 中的项目的方式:"serialize" 函数 returns a string 不是对象。因此,您需要继续向字符串中添加 post 数据,如:

...
data: 'action=foo&' + items // items is a string of the form "item[]=content&item[]=content..."
...

希望对您有所帮助!

检查一下并在 link 秒内向我们提供您需要的具体解决方案:

How do I PHP-unserialize a jQuery-serialized form?

我已经在 c9.io 上预览了您的代码,它工作正常。尝试使用这样的代码制作外部 ajax.php:

<?php
    $action = $_POST['action'];
    if ($action == 'foo') {
        $items = $_POST['items'];

        parse_str($_POST['items'], $params);
        var_dump($params);
    }
?>

然后制作类似:

$(document).ready(function(){
  var items = $('.mytable tbody').sortable();
  items = items.sortable('serialize');

  var ajaxRequest = function(){
    $.ajax({
      url: 'ajax.php',
      type: 'post',
      data: {
        action: 'foo',
        items
      },
      cache: false,
      complete: function(data){
        console.log(data)
      },
      error: function() {
        console.log('Error');
      }
    });
  };

  setInterval(function(){
    ajaxRequest();
  }, 2000);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<table class="mytable">
  <tbody>
    <tr id="item_01">
      <td>content</td>
    </tr>
    <tr id="item_02">
      <td>content</td>
    </tr>
    <tr id="item_03">
      <td>content</td>
    </tr>
    <tr id="item_04">
      <td>content</td>
    </tr>
    <tr id="item_05">
      <td>content</td>
    </tr>
  </tbody>
</table>

检查您的控制台和浏览器请求时间轴,您将看到未命名键数组 [0..n],其中包含您的脚本返回的值。

检查此 link 以了解如何使用此值: