数据表没有显示

时间:2013-05-14 06:34:10

标签: codeigniter datatables

我是jQuery和Ajax的新手,但我找到了一个使用CodeIgniter和datatables的示例组合。我确实以与示例相同的方式尝试,但我的数据表没有显示。

控制器

class User extends CI_Controller {
    private $content;
    private $data;
    function __construct(){
        parent::__construct();
        $this->load->model('usermodel');
        $this->init();
    }
    function init(){
        if( $this->session->userdata('username') == '' ) redirect('auth');
        $this->data['username'] = $this->session->userdata('username');
    }

    function index(){
        //$this->content = $this->load->view('userListView', null, true);
        $this->content = 'users';
        $this->data['content'] = $this->content;
        //$this->data['users'] = json_encode($this->usermodel->getDataTable());
        $this->load->view('home', $this->data);
    }

    function data() {
        //print_r($this->usermodel->getDataTable());
        echo json_encode($this->usermodel->getDataTable());
        exit;
    }

模型

class Usermodel extends CI_Model {
    function getListALL(){
        $strSQL = "SELECT * FROM mst_user";
        $qData = $this->db->query($strSQL);
        return $qData;
    }

    function getSingle($user_id){
        $strSQL = "SELECT * FROM mst_user WHERE id = '" . $user_id . "'";
        $qData = $this->db->query($strSQL);
        return $qData;
    }
    function getDataTable() {
        $sTable   = "mst_user";
        $aColumns = array( 'id', 'username', 'fullname', 'email');
        $sIndexColumn = "id";

        /*
         * Paging
         */
        $sLimit = "";
        if ( isset( $_POST['iDisplayStart'] ) && $_POST['iDisplayLength'] != '-1' ){
            $sLimit = "LIMIT ".addslashes( $_POST['iDisplayStart'] ).", " . addslashes( $_POST['iDisplayLength'] );

        }
        /*
           * Ordering
           */
        $sOrder = "";
        if ( isset( $_POST['iSortCol_0'] ) )
        {
            $sOrder = "ORDER BY  ";
            for ( $i=0 ; $i<intval( $_POST['iSortingCols'] ) ; $i++ )
            {
                if ( $_POST[ 'bSortable_'.intval($_POST['iSortCol_'.$i]) ] == "true" )
                {
                    $sOrder .= "`".$aColumns[ intval( $_POST['iSortCol_'.$i] ) ]."` ".
                        addslashes( $_POST['sSortDir_'.$i] ) .", ";
                }
            }

            $sOrder = substr_replace( $sOrder, "", -2 );
            if ( $sOrder == "ORDER BY" )
            {
                $sOrder = "";
            }
        }
        /*
           * Filtering
           * NOTE this does not match the built-in DataTables filtering which does it
           * word by word on any field. It's possible to do here, but concerned about efficiency
           * on very large tables, and MySQL's regex functionality is very limited
           */
        $sWhere = "";
        if ( isset($_POST['sSearch']) && $_POST['sSearch'] != "" )
        {
            $sWhere = "WHERE (";
            for ( $i=0 ; $i<count($aColumns) ; $i++ )
            {
                $sWhere .= "`".$aColumns[$i]."` LIKE '%".addslashes( $_POST['sSearch'] )."%' OR ";
            }
            $sWhere = substr_replace( $sWhere, "", -3 );
            $sWhere .= ')';
        }
        //echo $sWhere;exit;


        /* Individual column filtering */
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( isset($_POST['bSearchable_'.$i]) && $_POST['bSearchable_'.$i] == "true" && $_POST['sSearch_'.$i] != '' )
            {
                if ( $sWhere == "" )
                {
                    $sWhere = "WHERE ";
                }
                else
                {
                    $sWhere .= " AND ";
                }
                $sWhere .= "`".$aColumns[$i]."` LIKE '%".addslashes($_POST['sSearch_'.$i])."%' ";
            }
        }


        /*
           * SQL queries
           * Get data to display
           */
        $sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", implode("`, `", $aColumns))."` FROM $sTable $sWhere $sOrder $sLimit";
        //$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $stmt = $this->db->query($sQuery);
        //$stmt->setFetchMode(Zend_Db::FETCH_BOTH);
        $rResult = $stmt->result_array();
        //return $rResult;
        //echo $sQuery;exit;

        /* Data set length after filtering */
        $sQuery = " SELECT FOUND_ROWS() as FR";
        //$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $stmt = $this->db->query($sQuery);
        //$stmt->setFetchMode(Zend_Db::FETCH_BOTH);
        //$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $aResultFilterTotal = $stmt->result();
        //return $aResultFilterTotal;
        //$aResultFilterTotal = $stmt->fetchAll();
        $iFilteredTotal = $aResultFilterTotal[0]->FR;
        //echo $iFilteredTotal;exit;
        //print_r($aResultFilterTotal);exit;

        /* Total data set length */
        $sQuery = "SELECT COUNT(`".$sIndexColumn."`) as total FROM $sTable";
        //$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        //echo $sQuery;exit;
        $stmt = $this->db->query($sQuery);
        //$stmt->setFetchMode(Zend_Db::FETCH_BOTH);
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $aResultTotal = $stmt->result();
        $iTotal = $aResultTotal[0]->total;
        //echo $iTotal;exit;


        /*
           * Output
           */
        /* if(isset($_POST['sEcho'])) $sEcho = intval($_POST['sEcho']);
     else $sEcho = '';*/
        $output = array(
            "sEcho" => intval($_POST['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $iFilteredTotal,
            "aaData" => array()
        );

        foreach ($rResult as $aRow)
        {
            $row = array();
            for ( $i=0 ; $i<count($aColumns) ; $i++ )
            {
                if ( $aColumns[$i] == "version" )
                {
                    /* Special output formatting for 'version' column */
                    $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
                }
                else if ( $aColumns[$i] != ' ' )
                {
                    /* General output */
                    $row[] = $aRow[ $aColumns[$i] ];
                }
            }
            $output['aaData'][] = $row;
        }
        return $output;
    }

}

查看

<script type="text/javascript">
    $(document).ready(function() {
        $(".button").button();
        $('#table_list').dataTable({
            "bJQueryUI": true,
            "bServerSide": true,
            "sServerMethod": "POST",
            "sPaginationType": "full_numbers",
            "sAjaxSource": "<?php echo base_url();?>index.php/user/data"
        });
    });
</script>
<?php //echo $users;?>
<form class="form_element" action="">
    <div id="content_header"><h2>User - List</h2></div>
    <div style="float:right;padding-bottom:5px">
        <input type="button" value="Create New Record" onclick="window.location='user/form/add'" class="button">
    </div>
    <hr>

    <table id="table_list">
        <thead>
        <tr>
            <td>ID</td>
            <td width="200">User Name</td>
            <td>Full Name</td>
            <td>Email</td>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</form>

主页视图

<html>
<head>
<title>Admin MOS Template</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Copyright" content="">
<meta name="description" content="Admin MOS Template">
<meta name="keywords" content="Admin Page">
<meta name="author" content="">
<meta name="language" content="Bahasa Indonesia">

<link rel="shortcut icon" href="stylesheet/img/devil-icon.png"> <!--Pemanggilan gambar favicon-->
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>include/mos_admin/mos-css/mos-style.css"> <!--pemanggilan file css-->
<link type="text/css" href="<?php echo base_url(); ?>include/css/jquery.dataTables.css" rel="Stylesheet" />
<link type="text/css" href="<?php echo base_url(); ?>include/css/smoothness/jquery-ui-1.8.19.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="<?php echo base_url(); ?>include/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>include/js/jquery.dataTables.min.js"></script>
</head>

<body>
<?php
//print_r($users);
//echo $strFormType;
?>
<div id="header">
    <div class="inHeader">
        <div class="mosAdmin">
            <?php $this->load->view('headerview');?>
        </div>
        <div class="clear"></div>
    </div>
</div>

<div id="wrapper">
    <div id="leftBar">
        <?php $this->load->view('leftBarview'); ?>
    </div>

    <div id="rightContent">
        <?php
        if($content == 'changepass'){
            $this->load->view('changepassview');
        }
        else if($content == 'form'){
            $this->load->view('userformview');
        }
        else if($content == 'users'){
            $this->load->view('userlistview');
        }
        else{
            $this->load->view('rightContentview');
        }
        ?>
    </div>

    <div class="clear"></div>

    <div id="footer">
        <?php $this->load->view('footerview'); ?>
    </div>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您是否偶然将$ this-&gt;数据中的'data'对象与您拥有的数据方法(函数data()等)混淆?另外,对于使用ajax,你需要使用js代码,类似于jquery:

$(document).ready(function() { 
   $('#element_trigger_ajax').click(function(){

            var my_url = 'YOUR URL';//www.example.com/user/data
            params = {elem_id:$('#some_param').val()};
                $.ajax({
                    async:false,
                    type:'POST',
                    url: my_url,
                    data:params,
                    success: function(resp){
                        # This will load the response from your data method in the user controller within the element container div
                        $('div#element_container_that_will_change').html(resp);
                    }
                });

     });  

});