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 を埋めるデータにのみ関心があるため、何らかのテンプレート ライブラリを介して JavaScript で json オブジェクトを解析したくない場合を除き、ビュー出力のない ajax コントローラーが理想的です :?

<?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 に答える