3

我需要使用 Ajax 调用每 10 秒用我的数据库中的记录填充一个 div。我知道我必须先创建一个 JSON 对象,然后将它传递给 Ajax 函数。这就是我尝试过的。
//更新源 代码如下:

控制器

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class HomePage extends CI_Controller {

    public function index()
    {
       $this->load->model('home_page_model');
       $data['query'] = json_encode($this->home_page_model->onlineUsers());
       $this->load->view('homepage', $data);
    }
    public function AjaxUsers()
    {
//When I placed here the following, got an errow about query variable not defined
//the problem is the $data variable which when not loaded with the view
//throws en error. I don't know what to do further...
//$this->load->model('home_page_model');
//$data['query'] = json_encode($this->home_page_model->onlineUsers());

    }
}
?>

模型

<?php

    class home_page_model extends CI_Model {
        function __construct() {
            parent::__construct();
        }

        function onlineUsers() {
            $this -> db -> select('user_name,status,thumb') -> from('users') -> where('status', 'Online');
            $query = $this -> db -> get();
            if ($query -> num_rows > 0) {
                return $query -> result();

            } else {
                'There are no results';
            }   
        }
    }
    ?>

最后是我的观点

 <!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Welcome!</title>
        <link rel="stylesheet" type="text/css" href="<?php echo base_url() ?>css/csustyles.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script type="text/javascript">
setInterval(function()
{
$('.user-records').load('<?php echo base_url()?>index.php/HomePage/');
}, 1000);
</script>
</head>
    <body>
        <div id="container">
            <h1>Welcome to CodeIgniter!</h1>

<div id="body">
<div class="user-records"></div>
</div>
    <p class="footer">
    Page rendered in <strong>{elapsed_time}</strong> seconds
    </p>
</div>
</body>
</html>
4

2 回答 2

1

您只对填充 div 的数据感兴趣,因此没有视图输出的 ajax 控制器是理想的,除非您不想通过某种模板库在 javascript 中解析 json 对象:?

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax_Controller extends CI_Controller{

    public function __construct(){
        parent::__construct();
    }

    public function online_users(){

        //load the model
        //
        $this->load->model('UserModel');

        //grab the data
        $data = &$this->UserModel->usersOnline();

        if(!$data)//expecting array/object or boolean
        {
            echo json_encode(array(
               'error'   =>  1 
            ));
        }

        //send to the browser
        $this->output
             ->set_content_type('application/json')
             ->set_output(json_encode(array(
                 'error' =>  0,
                 'data' =>  $data
             )));
    }

}

-

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserModel extends CI_Model{

    public function __construct(){
        parent::__construct();
    }
    /**
     * usersOnline
     * 
     * @return mixed (boolean or array/object)
     * @throws Exception
     */
    public function usersOnline(){

        try
        {

           $data = $this->db
                 ->select('user_name, status, thumb')
                 ->from('users')
                 ->where('status', 'online')
                 ->get();

           if( !$data OR !$data->num_rows > 0)
               throw new Exception('No data found from last request__ ' . __CLASS__ . __METHOD__);

        }
        catch(Exception $e)
        {
            log_message('error', $e->getMessage());
            return false;
        }
        //we must have data?
        return $data;
    }
}

-

$route['users-online'] = 'ajax_controller/online_users';

-

<!-- Add this to head section -->
        <script>
            //Assign base_url as a global variable
            var BASEURL = "<?= base_url() ?>";
        </script>

-

<div id="usersOnline"></div>


        <script>
            (function($){

                var ajaxRequests = {

                    init : function(){
                        if(document.getElementById('usersOnline'))
                        {
                            this.onlineUsers;
                        }
                    },
                    onlineUsers : function(){

                        var scope = $("#usersOnline");

                        //ajax setup
                        var doAjax = function(div){
                            $.ajax({
                               url : BASEURL + "users-online",
                               type: 'GET',
                               context : div,
                               beforeSend : function(){
                                   $(this).html("<span class='loading-icon'>&nbsp;</span>");
                               },
                               success : function(callback){
                                   if(callback.error == 1)
                                   {
                                       return;
                                   }

                                   //$(this) == context => #usersOnline
                                   //
                                   //obviously the json object needs to be parsed first!!!!!!!
                                   //
                                   $(this).html(callback.data);

                               }
                            });
                        }

                        //run and run
                        window.setInterval(function(){
                            doAjax(scope);
                        }, 1000);
                    }
                }

                //ready?
                $(function(){
                   ajaxRequests.init(); 
                });

            })(jQuery);
        </script>
于 2012-12-10T19:49:37.850 回答
1

您需要制作一个实际输出所需数据的 AJAX 控制器。让我们调用它ajax_controller(尽管它也可以是现有控制器中的方法,例如homepage->online_users_ajax,它不必单独的控制器)。

然后,您需要使用 Javascript (jQuery) 每 10 秒调用一次新控制器。这是一个没有计时器的 jQuery 代码示例:

$('.online-users').load('<?php echo base_url('ajax_controller'); ?>');

所以,关键ajax_controller是渲染内容,jQuery 用渲染的数据填充现有的 div。

于 2012-10-30T22:07:34.850 回答