【问题标题】:Jquery Nestable output into mysql databaseJquery 可嵌套输出到 mysql 数据库
【发布时间】:2015-08-27 17:24:50
【问题描述】:

https://github.com/dbushell/Nestable 我正在使用 David Bushell 的上述源代码来创建一个可拖放编辑的嵌套列表。

我尝试编辑的“可排序”数据库有 4 列:id、name、parent_id、display_order

(`id`, `name`, `parent_id`, `display_order`)
(1, 'item 1', '2', 1),
(2, 'item 2', '0', 3),
(3, 'item 3', '', 1),
(4, 'item 4', '0', 2),
(5, 'item 5', '0', 1),
(6, 'item 6', '', 1),
(7, 'item 7', '', 1),
(8, 'item 8', '1', 1),
(9, 'item 9', '1', 2);

生成了两个有序列表,一个具有 parent_id 的所有整数值,其中 0 是顶层,一个顶层具有 parent_id=' '。上述数据库的输出显示在 JSFiddle 上:https://jsfiddle.net/c9m5r5p2/6/

我无法从 github 源添加 jquery.nestable.js,导致无法拖放。虽然添加了生成输出的函数

 var updateOutput = function(e)
{
    var list   = e.length ? e : $(e.target),
        output = list.data('output');
    if (window.JSON) {
        output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2));
    } else {
        output.val('JSON browser support required for this demo.');
    }
};

// output initial serialised data
updateOutput($('#nestable').data('output', $('#nestable-output')));
updateOutput($('#nestable2').data('output', $('#nestable2-output')));

但是,假设我将“项目 8”拖到顶层并让“项目 7”成为“项目 4”的子级,“输出 1”和“输出 2”将是:

output 1: [{"id":2,"children":[{"id":1},{"id":9}]},{"id":8},{"id":4,"children":[{"id":7}]},{"id":5}]

output 2: [{"id":3},{"id":6}]

由于缺乏关于 JQuery 的知识,我不知道如何将这些新值传递给(php?)函数并编辑数据库。如果没有“保存”按钮,这也可能吗?我很可能正在寻找一个简单的电话。

【问题讨论】:

  • 一个问题 - 如果您总是要使用一些嵌套结构并在数据库之间来回利用 JSON 序列化,那么您为什么还要费心尝试保存值的扁平层次结构表示在 MySQL 中与仅存储整个显示元素的结果 JSON 相比。您可以简单地从数据库中检索 JSON 并使用它在初始页面加载时重新创建嵌套控件。

标签: php jquery mysql


【解决方案1】:

听起来你只需要执行一个 ajax 请求。更新时调用一个名为updateOutput 的函数。我会在它的底部添加一个 ajax 调用类似:

updateOutput = function(e) {
    // All your processing here...

    // Ajax request.
    values = {output:output}
    $.post('/myurl', values, function(data) { 
      console.log(success)
    });
}

在 php 端,您将通过 post 接收数据并对其进行处理

function processDragUpdate()
{
    if (!isset($_POST['output'])
    {
      die('Missing data');
    } 
    $data = json_decode($_POST['output'])

    // Loop through data and process it and save to db.

    // Depending on your system you may need to exit here.
    die('success');
}

根据您的服务器设置方式,调用此函数可能就像创建一个名为 myurl.php 的文件一样简单。里面看起来像:

<?php
// Any required libraries to do your processing such as your mysql functions and database information and whatever library has the above function stored in it.
include_once '/libraries/stuff.php'

processDragUpdate();

更新

试图使代码更具体地用于用例,并添加了一些基本的如何 php 信息。仍然不确定我是否真的在回答这个问题。我只是在说如何使用基本的ajax。

【讨论】:

  • 可能是我正在寻找的东西,但是我不知道该怎么做,哪些变量在哪里。我已将输出功能添加到我的帖子中。你能用我的输出编辑你的答案吗?这是否在每次拖动后运行更新功能?我是否从不同的页面调用 phpfunction?
  • 如果上面的代码没有把你推向正确的方向,你可能需要研究一些基础知识从这里开始:w3schools.com/php/php_ajax_php.asp
  • @Pepe 添加了更多信息并尝试使其更具体地针对您的用例。这是否使它更清楚一点?另外请务必查看我之前评论中的链接。
  • @ danielson317 确实,我缺少有关 ajax 的基本知识。可能需要一些时间来准确地弄清楚一切,但我很确定这就是我想要的。一旦我有足够的时间弄清楚,我会接受你的回答。谢谢
  • 好吧,我做不到。我确实知道在哪里添加 ajax 请求(if 语句),但我不知道要传递哪个变量(或者如何添加一个值,所以我知道我在 php 中使用哪个顶级父级)。跨度>
【解决方案2】:

由于 danielson317 的回答没有给出完整的解决方案,我决定在更多搜索和询问后发布最终结果(Alter and post Jquery array)

为了将帖子拖放到 .php 文件中,必须在发生拖放的页面上进行一些编辑。添加了一个变量“last_touched”,以便能够知道是否发布了“nestable”或“nestable2”:

var last_touched = '';
var updateOutput = function(e)
{   
var list   = e.length ? e : $(e.target),
    output = list.data('output');
if (window.JSON) {
    output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2));

        $.post('process_update.php', 
            { 'whichnest' : last_touched, 'output' : output.val() }, 
            function(data) {
                console.log('succes')
            }
        );
} else {
         output.val('JSON browser support required for this demo.');
    }
};

// activate Nestable for list 1
$('#nestable').nestable({
    group: 1
})
.on('change', function(){ last_touched = 'nestable'; })
.on('change', updateOutput );

// activate Nestable for list 2
$('#nestable2').nestable({
    group: 1
})
.on('change', function(){ last_touched = 'nestable2'; })
.on('change', updateOutput );

// output initial serialised data
updateOutput($('#nestable').data('output', $('#nestable-output')));
updateOutput($('#nestable2').data('output', $('#nestable2-output')));

数组被发送到process_update.php,这里我们使用json_decode($_POST['output'],true);解码字符串数组。我们将此数组与数据库中的数据进行比较,计算差异并最后更新值。

<?php
include('config/setup.php');

//Nestable
if ($_POST['whichnest'] == 'nestable'){

    //Creating from_db unnested array
    $from_db = array();

    $sql = $dbc -> prepare("SELECT page_id, parent_id, display_order FROM pages WHERE parent_id != ''");
    $sql -> execute();
    $sql -> bind_result($page_id,$parent_id,$display_order);

    while($sql -> fetch()) {
        $from_db[$page_id] = ['parent'=>$parent_id,'order'=>$display_order];
    }

    //Function to create id =>[ order , parent] unnested array
    function run_array_parent($array,$parent){  
        $post_db = array();     
        foreach($array as $head => $body){
            if(isset($body['children'])){
                $head++;
                $post_db[$body['id']] = ['parent'=>$parent,'order'=>$head];
                $post_db = $post_db + run_array_parent($body['children'],$body['id']);
            }else{
                $head++;
                $post_db[$body['id']] = ['parent'=>$parent,'order'=>$head]; 
            }
        }

        return $post_db;
    }

    //Creating the post_db unnested array
    $post_db = array();
    $array = json_decode($_POST['output'],true);
    $post_db = run_array_parent($array,'0');

    //Comparing the arrays and adding changed values to $to_db
    $to_db =array();

    foreach($post_db as $key => $value){
        if( !array_key_exists($key,$from_db) || ($from_db[$key]['parent'] != $value['parent']) || ($from_db[$key]['order'] != $value['order'])){
            $to_db[$key] = $value;
        }   
    }

    //Creating the DB query
    if (count($to_db) > 0){
        $query = "UPDATE pages";
        $query_parent = " SET parent_id = CASE page_id";
        $query_order = " display_order = CASE page_id";
        $query_ids = " WHERE page_id IN (".implode(", ",array_keys($to_db)).")";

        foreach ($to_db as $id => $value){
            $query_parent .= " WHEN ".$id." THEN ".$value['parent'];
            $query_order .= " WHEN ".$id." THEN ".$value['order'];
        }
        $query_parent .= " END,";
        $query_order .= " END"; 

        $query = $query.$query_parent.$query_order.$query_ids;

        //Executing query
        $sql = $dbc -> prepare($query);
        $sql -> execute();
        $sql -> close();
    }
}
//nestable 2
elseif($_POST['whichnest'] == 'nestable2'){
    // More of the same!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2013-03-05
    相关资源
    最近更新 更多