如何通过使用数据库中的存储结构来还原jQuery UI可排序列表 [英] How to restore a jquery ui sortable list by using stored structure from db

查看:59
本文介绍了如何通过使用数据库中的存储结构来还原jQuery UI可排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的数据库中存储一个列表结构(基于此问题[1]:

I've tried to store a list-structure in my db (based on this question [1]: How to serialize a nested sortable ul list) and after that I need a way to restore/reset the list if the page is refreshed or load new based on the data from db.

是否有内置方法可以执行此操作?

在我的列表中,我使用嵌套元素来支持创建灵活的嵌套结构的方式.

In my list, I use nested elements to support the way to create flexible nested structure.

这是我已经拥有的

列表

<ul id="mysite" class="mysite editor-ul ui-sortable-handle ui-sortable">
  <li class="draggable editor-li editor-li-head ui-sortable-handle">Headline</li>
  <li class="draggable editor-li ui-sortable-handle" id="p-1">
    Item1
    <ul class="mysite editor-ul ui-sortable"></ul>
  </li>
  <li class="draggable editor-li ui-sortable-handle" id="p-5">
    Item 2
    <ul class="mysite editor-ul ui-sortable">
      <li class="draggable editor-li ui-sortable-handle" id="p-7" style="">
        Item 3
        <ul class="mysite editor-ul ui-sortable"></ul>
      </li>
      <li class="draggable editor-li ui-sortable-handle" id="p-6" style="">
        Item 4
        <ul class="mysite editor-ul ui-sortable"></ul>
      </li>
    </ul>
  </li>
</ul>

JS代码

$(function() {
  //$(".mysite").sortable({

  $(".mysite").sortable({
    connectWith: ".mysite",
    placeholder: "placeholder",
    update: function(event, ui) {
      var struct = [];
      var i = 0;

      $(".mysite").each(function(ind, el) {
        struct[ind] = {
          index: i,
          class: $(el).attr("class"),
          count: $(el).children().length,
          parent: $(el).parent().is("li") ? $(el).parent().attr("id") : "",
          parentIndex: $(el).parent().is("li") ? $(el).parent().index() : "",
          array: $(el).sortable("toArray"),
          serial: $(el).sortable("serialize")
        };
        i++;
      });
      console.log("Structure", struct);


      $.ajax({
        data: {
          "'.$this->security->get_csrf_token_name().'": "'.$this->security->get_csrf_hash().'",
          "job": "updateSiteStruc",
          "data": struct
        },
        type: "POST",
        url: "'.base_url().'"
      });


      var iArr = [];
      var iSer = [];
      $(".mysite:eq(0) li").each(function(ind, el) {

        if ($(el).attr("id") != undefined) {
          var label = $(el).attr("id");
        } else {
          return true;
        }

        iArr.push(label);
        var pre = label.slice(0, label.indexOf("-")) + "[]=";
        iSer.push(pre + label.slice(label.indexOf("-") + 1));
        if ($(el).children().eq(0).is("ul")) {
          $(el).find("li").each(function() {
            iArr.push($(this).attr("id"));
            iSer.push(pre + $(this).attr("id").slice(label.indexOf("-") + 1));
          });
        }
      });
      console.log("Items Array", iArr);
      console.log("Items Serial", iSer.join("&"));
    }
  }).disableSelection();

});

基于此,我存储结构

  • 通过ajax发送
  • 在数据库中保存json_encode($post['data'])

所以现在我在数据库中

"[{" array:["," p-1," p-5]," class:" mysite editor -ul ui-sortable-handle ui-sortable," count: "3","index":"0","parent":","serial":"p [] = 1& p [] = 5","parentIndex":"},{"class": "mysite editor-ul ui-sortable","count":"0","index":"1","parent":"p-1","serial":","parentIndex":"1" },{"array":["p-7","p-6"],"class":"mysite editor-ul ui-sortable","count":"2","index":"2" ,"parent":"p-5","serial":"p [] = 7& p [] = 6","parentIndex":"2"},{"class":"mysite editor-ul ui- sortable","count":"0","index":"3","parent":"p-7","serial":","parentIndex":"0"},{"class": "mysite editor-ul ui-sortable","count":"0","index":"4","parent":"p-6","serial":","parentIndex":"1" }]"

"[{"array": ["", "p-1", "p-5"], "class": "mysite editor-ul ui-sortable-handle ui-sortable", "count": "3", "index": "0", "parent": "", "serial": "p[]=1&p[]=5", "parentIndex": ""}, {"class": "mysite editor-ul ui-sortable", "count": "0", "index": "1", "parent": "p-1", "serial": "", "parentIndex": "1"}, {"array": ["p-7", "p-6"], "class": "mysite editor-ul ui-sortable", "count": "2", "index": "2", "parent": "p-5", "serial": "p[]=7&p[]=6", "parentIndex": "2"}, {"class": "mysite editor-ul ui-sortable", "count": "0", "index": "3", "parent": "p-7", "serial": "", "parentIndex": "0"}, {"class": "mysite editor-ul ui-sortable", "count": "0", "index": "4", "parent": "p-6", "serial": "", "parentIndex": "1"}]"

上面字符串的格式化版本:

Formatted version of string above:

"[{
  "array": ["", "p-1", "p-5"],
  "class": "mysite editor-ul ui-sortable-handle ui-sortable",
  "count": "3",
  "index": "0",
  "parent": "",
  "serial": "p[]=1&p[]=5",
  "parentIndex": ""
}, {
  "class": "mysite editor-ul ui-sortable",
  "count": "0",
  "index": "1",
  "parent": "p-1",
  "serial": "",
  "parentIndex": "1"
}, {
  "array": ["p-7", "p-6"],
  "class": "mysite editor-ul ui-sortable",
  "count": "2",
  "index": "2",
  "parent": "p-5",
  "serial": "p[]=7&p[]=6",
  "parentIndex": "2"
}, {
  "class": "mysite editor-ul ui-sortable",
  "count": "0",
  "index": "3",
  "parent": "p-7",
  "serial": "",
  "parentIndex": "0"
}, {
  "class": "mysite editor-ul ui-sortable",
  "count": "0",
  "index": "4",
  "parent": "p-6",
  "serial": "",
  "parentIndex": "1"
}]"

推荐答案

如果您要构建一个项目列表,这些项目可以作为字符串存储在数据库中,然后在HTML中以<ul>的形式构建,我建议使用更加复杂的结构,因此您可以在数据中建立更深层次的关系.

If you want to construct a list of items that can be stored as a string in a DB and then built out as <ul> in HTML, I would suggest using much more complex structure so you can have a deeper relationship within the data.

$(function() {

  var saveData;

  function makeObj(list) {
    var d = [];
    d.push({
      id: list.attr("id"),
      class: list.attr("class"),
      items: []
    });
    list.children("li").each(function(ind, el) {
      var item = {
        attr: {
          index: ind,
          id: $(el).attr('id') || "list-item-" + ind,
          class: $(el).attr('class'),
          style: $(el).attr('style')
        },
        label: el.firstChild.data.trim(),
        children: $("ul", el).length ? true : false,
        childObj: false
      };
      d[0].items.push(item);
    });
    return d;
  }

  function buildList(d, t) {
    console.log(d);
    $.each(d, function(key, item) {
      $("<li>", item.attr).html(item.label).appendTo(t);
    });
  }

  function makeSort(obj, cnwt) {
    obj.sortable({
      connectWith: cnwt,
      placeholder: "placeholder"
    });
  }

  function stringify(d) {
    return JSON.stringify(d);
  }

  function parse(s) {
    return JSON.parse(s);
  }

  $("#saveList").click(function(e) {
    var myData = makeObj($("#mySite"));
    console.log(myData);
    $.each(myData[0].items, function(key, item) {
      if (item.children) {
        myData[0].items[key].childObj = makeObj($("ul:eq(0) > li:eq(" + key + ") > ul"));
      }
    });
    console.log(stringify(myData));
    saveData = stringify(myData);
  });

  $("#loadList").click(function(e) {
    if (saveData.length) {
      console.log(saveData);
      var myData = parse(saveData);
      var newList = $("<ul>", {
        id: myData[0].id,
        class: myData[0].class
      }).insertAfter($(this));
      buildList(myData[0].items, newList);
      makeSort(newList, myData[0].class);
      $.each(myData[0].items, function(key, item) {
        if (item.children) {
          var sList = $("<ul>", {
            id: item.childObj[0].id || "",
            class: item.childObj[0].class
          }).appendTo($("li:eq(" + item.attr.index + ")", newList));
          buildList(item.childObj[0].items, sList);
          makeSort(sList, item.childObj[0].class);
        }
      });
    }
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<ul id="mySite" class="mysite editor-ul">
  <li class="draggable editor-li editor-li-head">Headline</li>
  <li class="draggable editor-li" id="p-1">Item1
    <ul class="mysite editor-ul"></ul>
  </li>
  <li class="draggable editor-li" id="p-5">Item 2
    <ul class="mysite editor-ul">
      <li class="draggable editor-li" id="p-7" style="">Item 3
        <ul class="mysite editor-ul"></ul>
      </li>
      <li class="draggable editor-li" id="p-6" style="">Item 4
        <ul class="mysite editor-ul"></ul>
      </li>
    </ul>
  </li>
</ul>
<button id="saveList">Save</button>
<button id="loadList">Load</button>

上面的示例专用于显示保存和加载功能.要进行测试,请单击保存",然后单击加载".该结构保存到字符串中,并放置在变量中.然后在加载时,从字符串中读取它并构建一个新副本.

The above example is specific to show the save and load features. To test, click Save and then click Load. The structure is saved to an string and placed in a variable. Then in load, it is read from the string and builds a new copy.

这与可排序无关,而与保存和加载有关.您可以使用update中的stringify(makeObj())将数据发送到数据库.如果列表更深,则必须对每个图层重复makeObj()几次.

This is less about the sortable and more about the saving and loading. You can use stringify(makeObj()) in update to send the data to your DB. If your list is deeper, you will have to repeat the makeObj() a few times for each layer.

从数据库获取数据时也是如此.它会以字符串形式返回,您可以在其中使用parse(),或者它将以对象的形式返回.如果您使用PHP来encode_json()并将JSON数据直接发送回脚本,则会是这种情况.

The same goes when you get the data from the DB. Either it will come back as a string where you can use parse() or it will come back as an object. This would be the case if you use PHP to encode_json() and send JSON data directly back to the script.

发回字符串:

buildList(parse(data), $(".target"));

发送回JSON:

buildList(data, $(".target"));

如您所见,它会变得非常复杂.找到一个可以为您完成繁重工作的插件可能会更好.请记住,这只是一个例子,可能并不是您所做工作的最佳例子.

As you can see, it can get pretty complex. It might be better to find a plugin that can do the heavy work for you. Remember this is just one example and maybe not the best one for what you're doing.

希望有帮助.

这篇关于如何通过使用数据库中的存储结构来还原jQuery UI可排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆