刷新页面时如何从Controller获取数据?

时间:2019-05-07 09:35:13

标签: php codeigniter

我正在创建一个仪表板,每次刷新页面时都需要在其中更新通知栏,以便在刷新页面时,必须执行控制器并将其从数据库返回到该页面。

做到这一点的最佳方法是什么?我在onload事件中尝试了一些方法,但是我似乎找不到一种使用它进入控制器的方法

目前我正在尝试: jQuery / Ajax:

 $( document ).ready(function() {
   $.ajax({
    type: 'POST',
    url:'<?=base_url('notificacoes') ?>'
   }).done(function(e){
    console.log(e);
    $('#notbadge').html(e);
   }) 
});

控制器:

<?php

    defined('BASEPATH') OR exit('No direct script access allowed');

    class Notificacoes extends CI_Controller {
        function __construct(){
            parent::__construct();
            $this->load->model('Notificacoes', '', TRUE);
            $this->load->model('Viatura', '', TRUE);
            $this->load->library('session');
        }

        public function index(){
            $matricula = $this->session->viatura;
            $viatura = $this->Viatura_model->read($matricula);

            return $viatura;

        }
    }

HTML徽章:

<span class="badge" id="notbadge"></span>

它不能在控制台上显示我的阵列,为什么?

1 个答案:

答案 0 :(得分:1)

要获取每次刷新页面的通知不是一个好主意,您应该为此使用javascript或angular js。尝试这样的事情。

$scope.getNotifications = function () {
        $.ajax({
            url: "<?php echo base_url() . "dashboard/getNotifications" ?>",
            type: 'POST',
            dataType: 'json',
            success: function (data, textStatus, jqXHR) {
                //console.log(data);
                $scope.notifications = data;
                $scope.total_unread_noti = data.total_unread_noti;
                $scope.$apply();
            }

        });
    };
    $scope.getNotifications();


    setInterval(function () {
        $scope.getNotifications();
    }, 3000);
相关问题