2013-03-15 69 views
0

我寫了一些codeigniter的代碼,當我點擊按鈕添加一個數據,並且表將ajax重新加載,而不是重新加載頁面。如何修改我的代碼?由於codeigniter ajax加載表

這是我的控制器

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

class Big_category extends CI_Controller { 

    function __construct() { 
    ... 
    } 

    function index() { 
    if($this->session->userdata('logged_in')) { 
     $this->page(0); 
    } else { 
     show_404('page'); 
    } 
    } 

    function page($page) { 
    .... 
    $data['pagelist']=$this->pagination->create_links(); 
    $data["main_content"] = "big_category_view"; 
    $this->load->view('template', $data); 
    } 

這是我的模型

class Big_category_model extends CI_Model 
{ 
    ... 
    function get_big_category($limit, $start) 
    { 
    $this->db->limit($limit, $start); 
    $query = $this->db->get_where('category1', array('c1_status' => 1)); //SELECT * FROM category1 
    return json_encode($query->result()); 
    } 

這是我的看法

... 
    <? $data = json_decode($all_big_category); ?> 
    <? foreach($data as $key => $value): ?> 
    <tr class="modify_tr"> 
     <td><?=($key+1)?></td> 
     <td id="td_id_<?=$value->c1_id?>" class="modify_td"> 

     <span id="c1_id_<?=$value->c1_id?>"><?=$value->c1_name?></span> 
     <form class="form-search td_id_<?=$value->c1_id?>"> 
      <input type="text" name="input_c1_id" id="input_c1_id_<?=$value->c1_id?>"> 
      <button class="btn modify" id="button_c1_id_<?=$value->c1_id?>" c1-id="<?=$value->c1_id?>" type="button"><i class="icon-edit"></i></button></td> 
     </form> 
     <td><button class="btn btn-danger"><i class="icon-remove-sign"></i></button></td> 
    </tr> 
    <? endforeach ?> 
    </table> 
    <?=$pagelist?> 
... 
+0

什麼是不工作?你的ajax呼叫在哪裏?你預期的結果與現在正在發生的事情是什麼? – 2013-03-15 04:26:42

+0

該視圖有寫了一些表代碼,如果我想使用ajax加載表,我應該再次寫這個代碼?我希望視圖代碼成爲模板,數據將填充在這張表中,我不知道,你能給我幾個指點嗎?謝謝 – lighter 2013-03-15 05:03:51

回答

3

這裏是你如何能做到這一點的簡單方法。

佈局(模板)

<html> 
<body> 
    <div><!--other stuff here--></div> 
    <div id = 'form_id'> 
    <?php echo $content?> 
    </div> 
</body> 
</html> 

控制器

function index() 
{ 
    if($this->input->is_ajax_request()){ 
     //load form here 
     $this->load->view('form');  
    }else{ 
     //this will load the form for the first time 
     //pass third parameter as TRUE so it will returned as string 
     //assigned to index content which will be displayed in layout 
     $data['content'] = $this->load->view('form',$data , TRUE);  

     //load template here 
     $this->load->view('template', $data);  
    } 
} 

JQuery的

$.ajax({ 
    type : 'POST', 
    url : '<?php echo site_url('controllername/index')?>', 
    data : '' // query string 
    success : function(formagain){ 
     $('#form_id').html(formagain); 
     //this will replace the content of div with new form 
    } 
}); 
+0

我有一個疑問,ajax的$數據,我會用一個lof字符串來建立一個表單嗎?(像這樣:var str =「

​​....」)。謝謝。 – lighter2013-03-16 15:35:18

+0

@Lighter在html中編寫php並不是一種好的做法,當CI給出單獨的視圖時,爲什麼我們不使用它? – 2013-03-16 17:50:26