2010-05-27 239 views
4

我試圖使jqgrid與codeigniter一起工作,但我做不到,我只想以json格式顯示錶格中的數據......但沒有任何反應..但我不知道我是什麼做錯了,我無法看到與我打電話內容的表。Jqgrid + CodeIgniter

我控制器

class Grid extends Controller 
{ 

    public function f() 
    { 

     $this->load->model('dbgrid'); 
     $var['grid'] = $this->dbgrid->getcontentfromtable(); 

     foreach($var['grid'] as $row) { 
     $responce->rows[$i]['id']=$row->id; 
     $responce->rows[$i]['cell']=array($row->id,$row->id_catalogo); 

     } 
    $json = json_encode($responce); 
     $this->load->view('vgrid',$json); 



    } 


    function load_view_grid() 
    { 

    $this->load->view('vgrid'); 


    } 


} 

我的模型

class Dbgrid extends Model{ 

function getcontentfromtable() 
{ 


    $sql = 'SELECT * FROM anuncios'; 
    $query = $this->db->query($sql); 
    $result = $query->result(); 


    return $result; 
} 

我的觀點(腳本)

$(document).ready(function() { 
jQuery("#list27").jqGrid({ 
     url:'http://localhost/sitio/index.php/grid/f', 
     datatype: "json", 
     mtype: "post", 
     height: 255, 
     width: 600, 
     colNames:['ID','ID_CATALOGO'], 
     colModel:[ 
      {name:'id',index:'id', width:65, sorttype:'int'}, 
      {name:'id_catalogo',index:'id_catalogo', sorttype:'int'} 


     ], 
     rowNum:50, 
     rowTotal: 2000, 
     rowList : [20,30,50], 
     loadonce:true, 
     rownumbers: true, 
     rownumWidth: 40, 
     gridview: true, 
     pager: '#pager27', 
     sortname: 'item_id', 
     viewrecords: true, 
     sortorder: "asc", 
     caption: "Loading data from server at once" 
    }); 

}); 

希望有人能幫助我

+0

哦,上帝我希望我可以編輯您的文章,並修正自己的錯誤使用'代碼Blocks'。你有'http:// localhost/sitio/index.php/grid/f'輸出的例子嗎? – Aren 2010-05-27 00:13:59

+0

哈哈....對不起 這是輸出{「rows」:{「」:{「id」:「11」,「cell」:[「11」,「225101503」]}}} – Ivan 2010-05-27 00:28:01

回答

3

由服務器產生的數據,你張貼在評論

{"rows":{"":{"id":"11","cell":["11","225101503"]}}} 

格式錯誤。輸出應該看起來像

{ 
    "total": "xxx", 
    "page": "yyy", 
    "records": "zzz", 
    "rows" : [ 
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]}, 
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]}, 
     ... 
    ] 
} 

(見http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data)。因此,它應該至少像

{"rows":[{"id":"11","cell":["11","225101503"]}]} 

一般來說,如果你定義一個jsonReader,你將能夠讀取幾乎所有的數據。您生產的數據只能通過用函數定義的jsonReader(參見http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#jsonreader_as_functionjquery with ASP.NET MVC - calling ajax enabled web service)進行操作。最簡單的方法是更改​​服務器代碼以生成標準formet中的數據(請參見上文),這可以通過標準jsonReader來實現。

還有一個小小的評論。使用sorttypedatatype: "json"沒有影響。參數sorttype僅適用於排序本地數據。在datatype: "json"的情況下,服務器將負責正確的數據排序。 jqGrid只向服務器發送列的名稱,用戶爲數據排序選擇哪一列。

+0

嗨Oleg,我可以生成正確的輸出的格式,但我仍然無法看到結果在表 這是我得到 {「行」:[ {「ID」:「1」,「細胞」:「1」, 「225101503」]}, {「id」:「3」,「cell」:[「3」,「225101503」]}, {「id」:「4」,「cell」:[「4」, 「225101503」]}, {「id」:「6」,「cell」:[「6」,「225101503」]}, {「id」:「5」,「cell」:[「5」, 「225101503」]}, {「id」:「7」,「cell」:[「7」,「452101500」]}, {「id」:「8」,「cell」:[「8」, 「330000000」]}, {「id」:「9」,「cell」:[「9」,「11 0101511「]}, {」id「:」10「,」cell「:[」10「,」110101502「]}, {」id「:」11「,」cell「:[」11「 225101503「]} ] } 我可以看到表中的數據,但在模型(MVC)之外。 – Ivan 2010-05-27 15:05:53

+0

有些重要的東西你不寫。你的代碼和數據並不完美,他們沒有關於頁面,總數和記錄的信息,但都應該工作。我將json數據保存在json.txt文件中,並使用JavaScript創建了一個小型html文件:ivan.htm。爲了讓所有的簡單,我剛剛取代後得到。所以試試這個http://www.ok-soft-gmbh.com/jqGrid/ivan0.htm。有用。爲了解決負行數問題,我設置了'rowNum:0',我們可以看到http://www.ok-soft-gmbh.com/jqGrid/ivan.htm。所以你在別的地方有你的問題。將我的html代碼與瀏覽器源代碼進行比較。 – Oleg 2010-05-27 15:57:01

+0

嗨奧列格, 感謝您的支持。我發現了什麼問題,當我想出來的時候,我想要自殺。我忘了包含一個js文件。 我在mtype中得到了'',因爲CI和jqGrid有不同的發佈方法CodeIgniter(POST)和jqGrid(GET)。 謝謝。 – Ivan 2010-05-27 17:29:30

3

我是代碼點火器中的新程序員。 我正在嘗試將jqgrid與代碼點火器集成在一起,七個小時後,我來到了一個成功的點,其中jqgrid和代碼點火器完全集成了搜索選項。

首先,在你的應用/模型目錄中寫一個模型。代碼是......

class JqgridSample extends CI_Model { 

    function getAllData($start,$limit,$sidx,$sord,$where){ 
    $this->db->select('id,name,email,passport,phone,fax,address'); 
    $this->db->limit($limit); 
    if($where != NULL) 
     $this->db->where($where,NULL,FALSE); 
    $this->db->order_by($sidx,$sord); 
    $query = $this->db->get('info',$limit,$start); 

    return $query->result(); 
    } 
} 

然後,在你的應用程序/控制器目錄中寫一個控制器。該代碼是

class Demo extends CI_Controller { 

function __construct() { 
    parent::__construct(); 
    $this->load->model('JqgridSample'); 
} 

function jqGrid(){ 
$this->load->view('showGrid'); 
} 

function loadData(){ 
    $page = isset($_POST['page'])?$_POST['page']:1; 
    $limit = isset($_POST['rows'])?$_POST['rows']:10; 
    $sidx = isset($_POST['sidx'])?$_POST['sidx']:'name'; 
    $sord = isset($_POST['sord'])?$_POST['sord']:'';   
    $start = $limit*$page - $limit; 
    $start = ($start<0)?0:$start; 

    $where = ""; 
    $searchField = isset($_POST['searchField']) ? $_POST['searchField'] : false; 
    $searchOper = isset($_POST['searchOper']) ? $_POST['searchOper']: false; 
    $searchString = isset($_POST['searchString']) ? $_POST['searchString'] : false; 

    if ($_POST['_search'] == 'true') { 
     $ops = array(
     'eq'=>'=', 
     'ne'=>'<>', 
     'lt'=>'<', 
     'le'=>'<=', 
     'gt'=>'>', 
     'ge'=>'>=', 
     'bw'=>'LIKE', 
     'bn'=>'NOT LIKE', 
     'in'=>'LIKE', 
     'ni'=>'NOT LIKE', 
     'ew'=>'LIKE', 
     'en'=>'NOT LIKE', 
     'cn'=>'LIKE', 
     'nc'=>'NOT LIKE' 
     ); 
     foreach ($ops as $key=>$value){ 
      if ($searchOper==$key) { 
       $ops = $value; 
      } 
     } 
     if($searchOper == 'eq') $searchString = $searchString; 
     if($searchOper == 'bw' || $searchOper == 'bn') $searchString .= '%'; 
     if($searchOper == 'ew' || $searchOper == 'en') $searchString = '%'.$searchString; 
     if($searchOper == 'cn' || $searchOper == 'nc' || $searchOper == 'in' || $searchOper == 'ni') $searchString = '%'.$searchString.'%'; 

     $where = "$searchField $ops '$searchString' "; 

    } 

    if(!$sidx) 
     $sidx =1; 
    $count = $this->db->count_all_results('info'); 
    if($count > 0) { 
     $total_pages = ceil($count/$limit);  
    } else { 
     $total_pages = 0; 
    } 

    if ($page > $total_pages) 
     $page=$total_pages; 
    $query = $this->JqgridSample->getAllData($start,$limit,$sidx,$sord,$where); 
    $responce->page = $page; 
    $responce->total = $total_pages; 
    $responce->records = $count; 
    $i=0; 
    foreach($query as $row) { 
     $responce->rows[$i]['id']=$row->id; 
     $responce->rows[$i]['cell']=array($row->name,$row->email,$row->passport,$row->phone,$row->fax,$row->address); 
     $i++; 
    } 

    echo json_encode($responce); 
} 
} 

最後,你在你的應用程序/ views目錄寫一個觀點..

<head> 

    <link rel="stylesheet" type="text/css" href="<?php echo base_url()?>application/views/css/custom-theme/jquery-ui-1.8.16.custom.css" /> 

    <link type="text/css" href="<?php echo base_url()?>application/views/css/ui.jqgrid.css" rel="stylesheet" /> 

    <link type="text/css" href="<?php echo base_url()?>application/views/css/plugins/searchFilter.css" rel="stylesheet" /> 

    <style> 
     html, body { 
      margin: 0; 
      padding: 0; 
      font-size: 75%; 
     } 
    </style> 

    <script type="text/javascript" src="<?php echo base_url(); ?>application/views/js/jquery-1.5.2.min.js"></script> 

    <script type="text/javascript" src="<?php echo base_url(); ?>application/views/js/i18n/grid.locale-en.js"></script> 

    <script type="text/javascript" src="<?php echo base_url(); ?>application/views/js/jquery.jqGrid.min.js"></script> 


    <title>Codeigniter With JQGrid</title> 
</head> 
<body> 
    <center> 
     <h1>Codeigniter With JQGrid</h1> 
    <?php 
     $ci =& get_instance(); 
     $base_url = base_url(); 
    ?> 
    <table id="list"></table><!--Grid table--> 
    <div id="pager"></div> <!--pagination div--> 
    </center> 
</body> 


<script type="text/javascript"> 
     $(document).ready(function(){ 
      jQuery("#list").jqGrid({ 
       url:'<?=$base_url.'index.php/demo/loadData'?>',  //another controller function for generating data 
       mtype : "post",    //Ajax request type. It also could be GET 
       datatype: "json",   //supported formats XML, JSON or Arrray 
       colNames:['Name','Email','Passport','Phone','Fax','Address'],  //Grid column headings 
       colModel:[ 
        {name:'name',index:'name', width:100, align:"left"}, 
        {name:'email',index:'email', width:150, align:"left"}, 
        {name:'passport',index:'passport', width:100, align:"right"}, 
        {name:'phone',index:'phone', width:100, align:"right"}, 
        {name:'fax',index:'fax', width:100, align:"right"}, 
        {name:'address',index:'address', width:100, align:"right"}, 
       ], 
       rowNum:10, 
       width: 750, 
       //height: 300, 
       rowList:[10,20,30], 
       pager: '#pager', 
       sortname: 'id', 
       viewrecords: true, 
       rownumbers: true, 
       gridview: true, 
       caption:"List Of Person" 
      }).navGrid('#pager',{edit:false,add:false,del:false}); 
     }); 
    </script> 

爲我自己,我的視圖文件在視圖目錄js和css中創建兩個文件夾。 和js foder我放置jqgrid包中找到的jquery-1.5.2.min.js,grid.locale-en.js(views/js/i18n /),jquery.jqGrid.min.js。

以同樣的方式jquery-ui-1.8.16.custom.css,ui.jqgrid.css需要的也是可用的jqgrid包。

運行全過程中,你必須創建一個數據庫名爲jqgrid_sample並在數據庫中創建一個名爲信息包含字段的表...

ID

電子郵件

護照

電話

傳真

地址

完蛋了。請享用。再見。

+0

$ responce沒有聲明。它應該是什麼? – Sander 2013-09-25 14:21:53

0

這些解決方案覆蓋了完整的JqGrid數據加載和CRUD。 這是非常簡單的任務。只需完成以下步驟即可享受。

  1. 寫型號就像下面

    class gridAction_model extends CI_Model { 
    
    public function __construct() { 
        $this->load->database(); 
    } 
    
    function getAllTeacherDesignation($start, $limit, $sidx, $sord, $where) { 
    
        $this->db->select('DesignationId,DesignationName,Description,Status'); 
        $this->db->limit($limit); 
        if ($where != NULL) 
         $this->db->where($where, NULL, FALSE); 
        $this->db->order_by($sidx, $sord); 
        $query = $this->db->get('TeacherDesignation', $limit, $start); 
    
        return $query->result(); 
    } 
    
    function insert_teacherDesignation($data) { 
        return $this->db->insert('TeacherDesignation', $data); 
    } 
    
    function update_teacherDesignation($id, $data) { 
        $this->db->where('DesignationId', $id); 
        return $this->db->update('TeacherDesignation', $data); 
    } 
    
    function delete_teacherDesignation($id) { 
        $this->db->where('DesignationId', $id); 
        $this->db->delete('TeacherDesignation'); 
    } 
    

    }

  2. 以下方法現在添加到控制器類

    class grid_action extends CI_Controller { 
    
    public function __construct() { 
        parent::__construct(); 
        $this->load->helper("form"); 
        $this->load->model("gridAction_model"); 
    } 
    
    public function loadTeacherDesignationData() { 
    
        $page = isset($_POST['page']) ? $_POST['page'] : 1; 
        $limit = isset($_POST['rows']) ? $_POST['rows'] : 10; 
        $sidx = isset($_POST['sidx']) ? $_POST['sidx'] : 'DesignationName'; 
        $sord = isset($_POST['sord']) ? $_POST['sord'] : ''; 
        $start = $limit * $page - $limit; 
        $start = ($start < 0) ? 0 : $start; 
    
        $where = ""; 
        $searchField = isset($_POST['searchField']) ? $_POST['searchField'] : false; 
        $searchOper = isset($_POST['searchOper']) ? $_POST['searchOper'] : false; 
        $searchString = isset($_POST['searchString']) ? $_POST['searchString'] : false; 
    
        if ($_POST['_search'] == 'true') { 
         $ops = array(
          'eq' => '=', 
          'ne' => '<>', 
          'lt' => '<', 
          'le' => '<=', 
          'gt' => '>', 
          'ge' => '>=', 
          'bw' => 'LIKE', 
          'bn' => 'NOT LIKE', 
          'in' => 'LIKE', 
          'ni' => 'NOT LIKE', 
          'ew' => 'LIKE', 
          'en' => 'NOT LIKE', 
          'cn' => 'LIKE', 
          'nc' => 'NOT LIKE' 
         ); 
         foreach ($ops as $key => $value) { 
          if ($searchOper == $key) { 
           $ops = $value; 
          } 
         } 
         if ($searchOper == 'eq') 
          $searchString = $searchString; 
         if ($searchOper == 'bw' || $searchOper == 'bn') 
          $searchString .= '%'; 
         if ($searchOper == 'ew' || $searchOper == 'en') 
          $searchString = '%' . $searchString; 
         if ($searchOper == 'cn' || $searchOper == 'nc' || $searchOper == 'in' || $searchOper == 'ni') 
          $searchString = '%' . $searchString . '%'; 
    
         $where = "$searchField $ops '$searchString' "; 
        } 
    
        if (!$sidx) 
         $sidx = 1; 
        $count = $this->db->count_all_results('TeacherDesignation'); 
        if ($count > 0) { 
         $total_pages = ceil($count/$limit); 
        } else { 
         $total_pages = 0; 
        } 
    
        if ($page > $total_pages) 
         $page = $total_pages; 
    
        $query = $this->gridAction_model->getAllTeacherDesignation($start, $limit, $sidx, $sord, $where); 
    
        $responce = new stdClass; 
    
        $responce->page = $page; 
        $responce->total = $total_pages; 
        $responce->records = $count; 
        $i = 0; 
    
        foreach ($query as $row) { 
         $responce->rows[$i]['id'] = $row->DesignationId; 
         $responce->rows[$i]['cell'] = array($row->DesignationId, $row->DesignationName, $row->Description, $row->Status); 
         $i++; 
        } 
        echo json_encode($responce); 
    } 
    
    public function crudTeacherDesignation() { 
    
        $oper = $this->input->post('oper'); 
        $id = $this->input->post('id'); 
        $DesignationId = $this->input->post('DesignationId'); 
        $DesignationName = $this->input->post('DesignationName'); 
        $Description = $this->input->post('Description'); 
        $Status = $this->input->post('Status'); 
    
        switch ($oper) { 
         case 'add': 
          $data = array('DesignationId' => $DesignationId, 'DesignationName' => $DesignationName, 'Description' => $Description, 'Status' => $Status); 
          $this->gridAction_model->insert_teacherDesignation($data); 
          break; 
         case 'edit': 
          $data = array('DesignationId' => $DesignationId, 'DesignationName' => $DesignationName, 'Description' => $Description, 'Status' => $Status); 
          $this->gridAction_model->update_teacherDesignation($DesignationId, $data); 
          break; 
         case 'del': 
          $this->gridAction_model->delete_teacherDesignation($DesignationId); 
          break; 
        } 
    } 
    

    }

  3. 在查看

    添加腳本
    <table id="gridDesignation"> </table> 
    
    <div id="pager"> </div> 
    
    
    
    
    
         $(document).ready(function() { 
    
        jQuery("#gridDesignation").jqGrid({ 
         url:'<?php echo base_url(); ?>grid_action/loadTeacherDesignationData',     
         mtype : "post",    //Ajax request type. It also could be GET 
         datatype: "json",   //supported formats XML, JSON or Arrray 
         colNames:['Designation ID','Designation Name','Description','Status'],  //Grid column headings 
         colModel:[ 
          {name:'DesignationId',index:'DesignationId', width:100, align:"left", editable:true, editrules:{required:true}}, 
          {name:'DesignationName',index:'DesignationName', width:150, align:"left",editable:true,editrules:{required:true}}, 
          {name:'Description',index:'Description', width:100, align:"left", sortable:false, editable:true,editrules:{required:true}}, 
          {name:'Status',index:'Status', width:100, align:"right",editable:true,editrules:{required:true}, 
           edittype:'select', editoptions:{value:"1:Active;0:InActive"} 
          } 
         ], 
         rownumbers: true, 
         rowNum:10, 
         width: 750, 
         height: "100%", 
         rowList:[10,20,30], 
         pager: jQuery('#pager'), 
         sortname: 'DesignationName', 
         autowidth: true, 
         viewrecords: true,    
         gridview: true, 
         ondblClickRow: function(id){    
          $("#gridDesignation").editGridRow(id, {closeAfterEdit:true,mtype:'POST'});     
         }, 
         sortorder: "desc",  
         editurl: '<?php echo base_url() ?>grid_action/crudTeacherDesignation', //URL Process CRUD 
         multiselect: false, 
         caption:"List Of Teacher Designation" 
        }).navGrid('#pager', 
        {view:true,edit:true,add:true,del:true}, 
        {closeOnEscape:true}, 
        {closeOnEscape:true}, 
        {closeOnEscape:true}, 
        {closeOnEscape:true}, 
        { 
         closeOnEscape:true,closeAfterSearch:false,multipleSearch:false, 
         multipleGroup:false, showQuery:false, 
         drag:true,showOnLoad:false,sopt:['cn'],resize:false, 
         caption:'Search Record', Find:'Search', 
         Reset:'Reset Search' 
        } 
    );   
    
    }); 
    
0

請予以警告這裏多次使用三 - 示例代碼具有SQL注入風險。在生成$where字符串之前,你應該避開你的searchString之類的東西;

替換此:

$where = "$searchField $ops '$searchString' "; 

本:

$searchString = mysql_real_escape_string($searchString); 
$where = "$searchField $ops '$searchString' ";