dongluo1853 2014-05-20 19:16
浏览 60
已采纳

Codeigniter - 使用jQuery刷新发送到视图的数据

I have no idea how to refresh the data sent to the view using jquery without refreshing the entire web site. I wrote something like this:

Controller:

public function blog($id) {

$data['comments'] = $this->Comments->findall('blog', $id);
$this->load->view('sites/blog', $data);

}

Model:

... reading from database ...

View:

<div id="comments">

reading data from $comments sent by controller blog

</div>

How can I refresh DIV comments using jQuery in the view that the function in the controller BLOG read a new refreshed number of comments? If I put in DIV comments code:

<? $this->load->view('sites/comments'); ?>

And refresh this DIV using jQuery this is unsuccessful because the data sent by the controller remain unchanged :/

  • 写回答

4条回答 默认 最新

  • dougu3290 2014-05-20 22:55
    关注

    I like to use the following approach:

    1st: create a view main.php with a <div id="blog_container"></div>. main.php is loaded from your default controller.

    2nd: create a view blogs.php, where you'll output your blog data like:

    view blogs.php

    <div class="comments">
        <?=$comments?>
    </div>
    

    3rd: add a jquery ajax function to main.php, calling a controller function e.g. get_blogs(). This function queries your blog data and loads blogs.php, but with a trick: you'll set it to true, so the output is a html-string

    ajax function:

       function refresh_blog(){
          $.ajax({
            url:        url to your controller,
            type:       'POST',
            cache:      false,
            success: function(html){                    
                $('#blog_container').html(html)
            }           
          });
       }
    

    controller get_blogs:

    get_blogs(){
        // below would better be in a model
        $html='';
        $query = $this->db->get('my_blogs');        
        $blogs = $query->result();
    
        foreach ($blogs as $row){
           // data from your table my_blogs column comments
              $data['comments']=$row->comments;
              $html.=$this->load->view('blogs', $data, true); // returns view as data
        };
        echo html;
    }
    

    note: you can call your ajax function either on a click event or automatically every x seconds (e.g. with setTimeout() )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?