首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

CodeIgniter 實現 AJAX 分頁、全選反選與批量刪除完整教學

     編輯:PHP 綜合知識

專案背景與技術棧

CodeIgniter 作為輕量級 PHP 框架,配合 jQuery AJAX 可快速構建現代化的後台管理介面。本文完整展示一個包含「AJAX 分頁、搜尋、狀態切換、全選/反選/不選、批量刪除、即點即改、Excel 匯出」功能的使用者管理模組。

前端核心 JavaScript 實現

1. AJAX 分頁與搜尋

function ajax_page(page) {
    var sou = $('#sou').val();
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "",
        data: "page=" + page + "&sou=" + sou,
        success: function(data) {
            var str = "<table border='1' style='text-align:center'>";
            str += "<tr><td><input type='checkbox' class='quan'/></td><td>ID</td><td>用戶名</td><td>操作</td></tr>";
            $.each(data.list, function(i, item) {
                var locks = item.state == 0 
                    ? "<a href='javascript:void(0)' class='lok' fla='" + item.id + "' id='lock" + item.id + "'>未鎖定</a>"
                    : "<a href='javascript:void(0)' class='lok' fla='" + item.id + "' id='lock" + item.id + "'>鎖定</a>";
                str += "<tr id='av" + item.id + "'>";
                str += "<td><input type='checkbox' class='ss' value='" + item.id + "'/></td>";
                str += "<td>" + item.id + "</td><td>" + item.name + "</td><td>" + locks + "</td>";
                str += "</tr>";
            });
            str += "<tr><td><input type='button' id='pdel' value='批量刪除'></td></tr></table>";
            str += data.pagestr;
            $('#content').html(str);
        }
    });
}

2. 狀態切換(鎖定/解鎖)

$(document).on('click', '.lok', function() {
    var id = $(this).attr('fla');
    $.ajax({
        type: "POST",
        url: "",
        data: "id=" + id,
        success: function(msg) {
            $('#lock' + id).html(msg == 1 ? "鎖定" : "未鎖定");
        }
    });
});

3. 批量刪除

$(document).on('click', '#pdel', function() {
    var ids = $('.ss'), str = "";
    $.each(ids, function(i, item) {
        if (ids[i].checked) str += ',' + ids[i].value;
    });
    var new_str = str.substr(1);
    $.ajax({
        type: "POST",
        url: "",
        data: "new_str=" + new_str,
        success: function(msg) {
            $.each(ids, function(i, item) {
                if (ids[i].checked) $('#av' + ids[i].value).remove();
            });
        }
    });
});

4. 全選 / 反選 / 全不選

// 全選(複選框)
$(document).on('click', '.quan', function() {
    var ids = $('.ss');
    $.each(ids, function(i, item) { ids[i].checked = this.checked; });
});

// 全選 / 全不選 / 反選(按鈕版)
$('.quan').click(function() { $('input:checkbox').prop('checked', true); });
$('.bu').click(function() { $('input:checkbox').prop('checked', false); });
$('.fan').click(function() { $('.checks').prop('checked', function(i, v) { return !v; }); });

5. 即點即編輯(Inline Edit)

$(document).on('click', '.ss', function() {
    var id = $(this).attr('id'), con = $(this).text();
    $(this).parent().html("<input type='text' id='" + id + "' class='aa' value='" + con + "'>");
    $('.aa').focus().val(con);
});

$(document).on('blur', '.aa', function() {
    var id = $(this).attr('id'), cons = $(this).val();
    $(this).parent().html("<span id='" + id + "' class='ss'>" + cons + "</span>");
    $.ajax({
        type: "POST",
        url: "",
        data: "id=" + id + "&cons=" + cons
    });
});

6. Excel 匯出

$(document).on('click', '#chu', function() {
    var sou = $('#sou').val();
    location.href = "?sou=" + sou;
});

後端控制器實現

1. AJAX 分頁邏輯

public function ajax_page() {
    $sou = $this->input->post('sou');
    $count = $this->db->where("name like '%$sou%'")->count_all_results("peng");
    $number = 3;
    $this->session->set_userdata('number', $number);
    $pagecount = ceil($count / $number);
    $page = isset($_POST['page']) ? $_POST['page'] : 1;
    $this->session->set_userdata('page', $page);
    $start = ($page - 1) * $number;
    
    $arr['list'] = $this->db->where("name like '%$sou%'")->limit($number, $start)->get("peng")->result_array();
    
    $up_page = $page - 1 < 1 ? 1 : $page - 1;
    $down_page = $page + 1 > $pagecount ? $pagecount : $page + 1;
    
    $str = "<a href='javascript:void(0)' onclick='ajax_page($up_page)'>上一頁</a>";
    for ($i = 1; $i <= $pagecount; $i++) {
        $str .= $i == $page ? "--<b>$i</b>" : "--<a href='javascript:void(0)' onclick='ajax_page($i)'>$i</a>";
    }
    $str .= "--<a href='javascript:void(0)' onclick='ajax_page($down_page)'>下一頁</a>";
    
    $arr['pagestr'] = $str;
    echo json_encode($arr);
}

2. 狀態切換

public function upds() {
    $id = $this->input->post('id');
    $arr = $this->db->get_where("peng", "id='$id'")->row_array();
    if ($arr['state'] == 0) {
        $this->db->where("id='$id'")->update("peng", ['state' => 1]);
        echo "1";
    } else {
        $this->db->where("id='$id'")->update("peng", ['state' => 0]);
        echo "2";
    }
}

3. 批量刪除

public function pdels() {
    $str = $this->input->post('new_str');
    $this->db->where("id in($str)")->delete("peng");
}

安全性與最佳實踐提醒

  • SQL 注入防護:原代碼直接拼接 SQL,生產環境務必使用 Query Binding:$this->db->where_in('id', explode(',', $str))->delete('peng')
  • CSRF 保護:AJAX 請求應攜帶 CI 的 CSRF Token
  • 權限驗證:批量刪除等敏感操作需在後端二次驗證用戶權限
  • 輸出編碼:動態拼接 HTML 時注意 XSS 風險,建議使用模板引擎或 htmlspecialchars()

總結

本文提供了一套完整的 CodeIgniter + jQuery AJAX 後台管理基礎模組,涵蓋分頁、搜尋、狀態切換、複選框操作、批量刪除、行內編輯與資料匯出等常見功能。開發者可直接套用並根據業務需求擴展,同時務必注意安全性加固。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved