You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter中整合jQuery Nested Sortable拖拽插件(基于mysqli)

把jQuery Nested Sortable的保存逻辑整合到CodeIgniter

作为CodeIgniter新手,别担心,咱们一步步把你的原生PHP逻辑迁移到CI的MVC结构里,这样既符合框架规范,也更容易维护和扩展。

第一步:先理清楚你的核心逻辑

你的save.php核心是接收前端传来的JSON排序数据,递归解析每个节点的层级关系(父ID、排序值),然后更新数据库。先把截断的核心逻辑补全(符合Nested Sortable的常规处理逻辑):

<?php require("config.php"); 
$data = json_decode($_POST['data']); 

function parseJsonArray($jsonArray, $parentID = 0) {
    $return = array();
    foreach ($jsonArray as $index => $subArray) {
        $return[] = array(
            'id' => $subArray->id,
            'parent_id' => $parentID,
            'order' => $index + 1 // 排序值从1开始计数
        );
        if (isset($subArray->children)) {
            $return = array_merge($return, parseJsonArray($subArray->children, $subArray->id));
        }
    }
    return $return;
}

// 解析后批量更新数据库
$parsedData = parseJsonArray($data);
// 原生PHP的数据库更新逻辑...
?>

接下来我们把这个逻辑拆分到CI的控制器和模型中。

第二步:创建控制器(Controller)

在application/controllers/目录下新建Sortable.php,用来接收前端POST请求,调用模型处理数据:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sortable extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // 加载模型(CI会自动连接数据库,前提是你在config里配置好了数据库信息)
        $this->load->model('Sortable_model');
    }

    // 处理排序保存的核心方法
    public function save_order() {
        // 用CI的输入类获取POST数据,比直接用$_POST更安全
        $json_data = $this->input->post('data');
        if (!$json_data) {
            echo json_encode(['status' => 'error', 'message' => '没有接收到排序数据']);
            return;
        }

        $data = json_decode($json_data);
        if (json_last_error() !== JSON_ERROR_NONE) {
            echo json_encode(['status' => 'error', 'message' => 'JSON数据格式错误']);
            return;
        }

        // 调用模型的方法完成数据库更新
        $result = $this->Sortable_model->update_sortable_order($data);

        if ($result) {
            echo json_encode(['status' => 'success', 'message' => '排序更新成功']);
        } else {
            echo json_encode(['status' => 'error', 'message' => '排序更新失败']);
        }
    }
}
?>

第三步:创建模型(Model)

在application/models/目录下新建Sortable_model.php,负责处理递归解析和数据库操作:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sortable_model extends CI_Model {

    // 递归解析JSON数组,生成需要更新的数据集
    private function parse_json_array($jsonArray, $parentID = 0) {
        $return = array();
        foreach ($jsonArray as $index => $subArray) {
            $return[] = array(
                'id' => $subArray->id,
                'parent_id' => $parentID,
                'order' => $index + 1 // 这里的字段名要和你数据库的排序字段一致,比如叫position就改成position
            );
            if (isset($subArray->children)) {
                $return = array_merge($return, $this->parse_json_array($subArray->children, $subArray->id));
            }
        }
        return $return;
    }

    // 批量更新数据库的排序关系
    public function update_sortable_order($data) {
        $parsed_data = $this->parse_json_array($data);

        // 开启数据库事务,确保所有更新要么全成功,要么全回滚
        $this->db->trans_start();

        foreach ($parsed_data as $item) {
            // 替换成你实际的表名和字段名,比如你的表是menu,就把categories改成menu
            $this->db->where('id', $item['id']);
            $this->db->update('categories', array(
                'parent_id' => $item['parent_id'],
                'order' => $item['order']
            ));
        }

        $this->db->trans_complete();

        // 返回事务执行结果
        return $this->db->trans_status() !== FALSE;
    }
}
?>

第四步:调整前端请求URL

原来的AJAX请求指向save.php,现在改成CI控制器的方法,记得用CI的base_url()函数生成正确的URL:

// 假设你原来的AJAX代码是这样的
$.ajax({
    url: '<?php echo base_url('sortable/save_order'); ?>',
    type: 'POST',
    data: { data: JSON.stringify(nestedSortableArray) },
    success: function(response) {
        const res = JSON.parse(response);
        if (res.status === 'success') {
            alert('排序已保存');
        } else {
            alert('保存失败:' + res.message);
        }
    },
    error: function() {
        alert('请求出错,请重试');
    }
});

关键注意事项

  1. 数据库配置:确保你已经在application/config/database.php里正确配置了数据库连接信息(主机、用户名、密码、数据库名)。
  2. CSRF保护:如果你的CI开启了CSRF保护(默认是开启的),需要在AJAX请求里带上CSRF token:
    // 在POST数据里添加token
    data: {
        data: JSON.stringify(nestedSortableArray),
        <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
    }
    
  3. 字段匹配:模型里的表名、字段名(比如parent_id、order)一定要和你实际的数据库结构一致,别直接抄代码,要根据自己的表修改。

这样就把你的原生save.php逻辑完全迁移到CodeIgniter的MVC结构里了,符合框架的最佳实践,后续维护也更方便。

内容的提问来源于stack exchange,提问作者Ayush Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:22:28