简体   繁体   English

CodeIgniter-使用setInterval自动从数据库获取数据

[英]CodeIgniter - getting data from database automatically using setInterval

In codeigniter, I want to display the change in the database automatically without reloading the page so i use ajax to run a controller function in my view. 在codeigniter中,我想自动显示数据库中的更改,而无需重新加载页面,因此我在自己的视图中使用ajax运行控制器功能。 I'm using setInterval to run the function over and over again until the controller function listen_auth returns 1 and the view displays 1. 我正在使用setInterval一遍又一遍地运行该函数,直到控制器函数listen_auth返回1并且视图显示1。

VIEW: 视图:

<h4 class="qr-title" id="status"></h4>

<script>
    var username = <?php echo(json_encode($username)); ?>;

    function checkAuthStatus() {
        setInterval(getStatus, 1000);
    }

    function getStatus() {
        var isAuth = <?php echo(json_encode($isAuth)); ?>;
        $.ajax({
            url: '<?php echo base_url('auth/listen_auth'); ?>',
            type: 'post',
            data: {username:username},
            success: function(data){
                console.log(data);
            }
        });
        document.getElementById("status").innerHTML = isAuth;
    }
</script>

here's the listen_auth() function in my CONTROLLER: 这是我的控制器中的listen_auth()函数:

public function listen_auth(){
        $username = $this->input->post('username');
        $isApproved = $this->adminmodel->get_auth($username);
        if($isApproved == 1){
            return 1;
        } else{
            return 0;
        }
    }

The problem is that isAuth variable will only change once the page has been reloaded... Am I doing something wrong? 问题是,只有重新加载页面后, isAuth变量才会更改...我做错了吗? Or is there any better way to do this? 还是有更好的方法来做到这一点?

您需要声明$ isAuth并在ajax请求中分配其值,因为php变量在没有服务器请求的情况下不会更改其值。

The function from server 'listen_auth()' should print text not return. 服务器“ listen_auth()”中的函数应打印文本而不返回。

public function listen_auth(){
    $username = $this->input->post('username');
    $isApproved = $this->adminmodel->get_auth($username);
    if($isApproved == 1){
        echo 1;
    } else{
        echo 0;
    }
}

And then get the answer from server in AJAX request: 然后从服务器在AJAX请求中获得答案:

<script>
var username = <?php echo(json_encode($username)); ?>;

function checkAuthStatus() {
    setInterval(getStatus, 1000);
}

function getStatus() {
    var isAuth = <?php echo(json_encode($isAuth)); ?>;
    $.ajax({
        url: '<?php echo base_url('auth/listen_auth'); ?>',
        type: 'post',
        data: {username:username},
        success: function(data){
            document.getElementById("status").innerHTML = data;
        }
    });

}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM