我需要使用 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>