如何在 jQuery 中序列化多个可排序项目和子项目

How to serialize multiple sortable items and subitems in jQuery

我使用的是 Sortable items and subitems in list on jQuery ui sortable 的解决方案,一切正常,我唯一不明白的是序列化它们,这样我就可以相应地修改数据库。

https://jsfiddle.net/5zwgx45q/

我根本不知道 jQuery 或 JavaScript 所以这对我来说就是一片丛林。

我正在使用以下代码在其他地方实现我想要的。

$(document).ready(function() {

    var data;

    // Sort the parents
    $(".sortProducts").sortable({
        containment: "document"
        , group: 'serialization'
        , items: "> div"
        , handle: ".move"
        , tolerance: "pointer"
        , cursor: "move"
        , opacity: 0.5
        , revert: 300
        , placeholder: "productPlaceholder"
        , start: function(e, ui) {
            ui.placeholder.height(ui.helper.outerHeight());
        }
        , stop: function(event, ui) {
            data = $(".sortProducts").sortable("toArray", {
                attribute: 'data-id'
            });
        }

    });

    $("#saveOrder").click(function() {
        $.ajax({
            url: 'process/sortMenu.php?action=products'
            , type: 'POST'
            , dataType: 'json'
            , data: {
                newOrder: JSON.stringify(data)
            },

            success: function(output) {
                alert('Menu order changed successfully!');
            },

            error: function(output) {
                alert($(output['responseText']).text());
            }
        });
    });
})

它序列化一切

data = $(".sortProducts").sortable("toArray", {attribute: 'data-id'});

我可以将更改应用到数据库。这里的区别是我有两组可排序对象(parent 和 children)所以我不知道如何让序列化同时适用于这两个对象以及如何使用它。

children 可以在 parents 之间移动,我需要能够在数据库中反映出来。所以我不知何故需要知道哪个 child 属于哪个 parent.

数据像论坛一样存储在数据库中。

ID | MenuID | Name | Position
-----------------------------
1  |   0    | Nme1 |    1
2  |   1    | Nme2 |    2
3  |   1    | Nme3 |    3
4  |   0    | Nme4 |    4

如果 MenuID 为 0,则为 parent。如果 MenuID 为 1,则 parent 是 ID = 1 的项目。

你可以这样做:

function getSortableList(className){
  var sortables = $(className);
  var myArray = new Array();
  sortables.each(function() {
    myArray = myArray.concat($(this).sortable('toArray'));
  })
  // Show length of array
  alert(myArray.length);
}

Online demo (jsFiddle)

编辑

要根据您的数据库转换项目 table 您可以使用以下代码:

function createRecordsFromSortableList() {
  var sortables = $(".menuItems");
  var records = [];

  sortables.each(function() {
    var currentParent = this;
    var myRecord = new record($(this).attr("id"), "0", $(this).closest(".menuGroup").find('h2').text());
    records.push(myRecord);
    $(this).find('.menuItem').each(function() {
      var myRecord = new record($(this).attr("id"), $(currentParent).attr("id"),$.trim($(this).text().replace(/[\t\n]+/g,' ')));
      records.push(myRecord);
    });

  });
  alert("Please see records in console.");
  console.log(records);
}

function record(id, menuId, name) {
  this.id = id;
  this.menuId = menuId;
  this.name = name;
}

Online demo (get records from sortable list)