在 codeigniter 中使用 jquery/ajax 刷新特定的 div

Refreshing a specific div using jquery/ajax in codeigniter

我有一个带有订单的 table,我正在尝试每 5 秒刷新一次 table,而不是刷新整个页面。 经过一些研究,我发现我需要使用这个功能:

<script>
$(document).ready(function(){
    refreshTable();
});
function refreshTable(){
    $('#the_div_you_need_to_refresh').load('path', function(){
        setTimeout(refreshTable, 5000);
    });
}

问题是我真的不明白我应该在 .load('path') 中放什么,因为如果我这样写,它会使我的 header 加倍,它会给我一个错误:

.load('<?php echo base_url('page name')?>',function(){
         <--function content-->
})

我的浏览页面是这样的:

<h2><?= $title;?></h2>
<div id="table_container">
    <table class="table table-striped table-hover" id="orders_table">
        <thead>
        <--content-->
        </thead>
        <tbody>
        <?php foreach($orders as $order):?>
            <tr class="active">
                <--content-->
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

我的控制器是这样的:

public function index(){

            if(!$this->session->userdata('logged_in')){
                redirect('users/login');
            }
            $data['title'] = "Comenzi";
            $data['orders'] = $this->order_model->get_orders();

            $this->load->view('templates/header');
            $this->load->view('orders/comenzi',$data);
            $this->load->view('templates/footer');
        }

你能解释一下我应该怎么做吗?

这是一个异步请求,用于从其他资源获取数据。为了在每 5 秒后加载新数据,您需要创建一个 page/controller,它将被此加载函数命中。

你需要在path变量中输入这个page/controller的url。

该控制器应该 return 您将使用 jquery

添加或替换的新数据

尝试在您的控制器中创建新操作。例如。

public function newData(){

    if(!$this->session->userdata('logged_in')){
        redirect('users/login');
    }
    $data['title'] = "Comenzi";
    $data['orders'] = $this->order_model->get_orders();

    $this->load->view('path_to_your_table_view',$data);
}

在你的脚本中

<script>
    $(document).ready(function(){
        refreshTable();
    });

    function refreshTable(){
        $("#table_container").empty();
        $("#table_container").load("<?php echo base_url('newData')?>", function(){
            setTimeout(refreshTable, 5000);
        });
    }
</script>

希望对您有所帮助。