【问题标题】:Refreshing a specific div using jquery/ajax in codeigniter在 codeigniter 中使用 jquery/ajax 刷新特定的 div
【发布时间】:2018-08-31 16:43:25
【问题描述】:

我有一张订单表,我尝试每 5 秒刷新一次表,而不刷新整个页面。 经过一番研究,我发现我需要使用这个功能:

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

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

.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');
        }

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

【问题讨论】:

    标签: php jquery ajax codeigniter refresh


    【解决方案1】:

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

    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>
    

    我希望它会有所帮助。

    【讨论】:

    • 该脚本只会删除我的整个表格,仅此而已。也许重要的是要说在 我有一个 foreach 在 products 数组中循环
    • 您需要创建循环新行数据并将其附加到 div 的新视图页面
    • omg,我太糟糕了...... -.- 所以“path_to_your_table_view”将是一个新视图,但我如何将新数据放在第一个表中?抱歉这么多问题,但我真的不明白这个
    【解决方案2】:

    这是一个异步请求,用于从其他资源获取数据。为了每 5 秒加载一次新数据,您需要创建一个页面/控制器,该页面/控制器将被此加载函数命中。

    您需要在path 变量中输入此页面/控制器的url。

    该控制器应该返回您将使用 jquery 附加或替换的新数据

    【讨论】:

    • 嗯,好的,我会尝试这样做,我会回来更新编辑:在 thtat 控制器中,我需要向数据库发出新请求,对吗?
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签