Jquery Nestable输出到mysql数据库

时间:2015-08-27 17:24:51

标签: php jquery mysql

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

我要编辑的数据库'sortable'有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')));

但是,想象一下,我会将'item 8'拖到顶层,让'item 7'成为'item 4'的孩子,'Output 1'和'Output 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?)函数并编辑数据库。如果没有“保存”按钮,这也可以吗?我很可能正在寻找一个轻松的电话。

2 个答案:

答案 0 :(得分:1)

听起来你只需要执行ajax请求。在更新时,您调用一个名为updateOutput = function(e) { // All your processing here... // Ajax request. values = {output:output} $.post('/myurl', values, function(data) { console.log(success) }); } 的函数。我会在它的底部添加一个ajax调用类似于:

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');
}

在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();

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

Process

更新

试图使代码更具体的用例,并添加了一些基本的如何PHP信息。我还不确定我是否回答了这个问题。我刚才谈到了如何使用基本的ajax。

答案 1 :(得分:1)

由于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!