CI是一個PHP MVC框架,JQuery是一個JS庫,用AJAX實現發送與顯示。
直接上代碼:
Controller: chat.php
class Chat extends CI_Controller {//CI中類名首字母大寫
function __construct() {
parent::__construct();
$this->load->model('chat_model');//加載chat_model
$ip_list = array('172.18.59.251', '172.18.58.238', '172.18.58.248', '172.18.58.243');
$ip = $this->input->ip_address();
if (!in_array($ip, $ip_list)) show_404();//簡單的過濾了幾個IP
}
//home page
function index() {
$this->load->helper(array('url', 'form'));
$this->load->view('index/index');
}
//send message
function send() {
$data = $this->input->post();
if (empty($data)) return false;
if ($this->chat_model->save($data) == false) {//保存
echo '0';
}
}
//show the last N message
function show() {
$data = $this->chat_model->getSome(5);//獲取N條消息
$data = array_reverse($data);//反轉數組
$chat['content'] = $data;
$string = $this->load->view('index/show', $chat, TRUE);//視圖放入string變量中
echo $string;//返回給ajax請求
}
//show all message
function more() {
$data = $this->chat_model->getAll();
$chat['content'] = $data;
$this->load->view('index/more', $chat);
}
}
Model: chat_model.php
class Chat_model extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
//save message
function save($data) {
$data['ip'] = $this->input->ip_address();
$data['send_date'] = date('Y-m-d H:i:s');
if ($this->db->insert('tb_chat', $data) == false) {
return false;
}
return true;
}
//get N message
function getSome($limit) {
if ($limit == 0) return false;
$this->db->select('username, content, send_date');
$this->db->from('tb_chat');
$this->db->order_by('send_date', 'DESC');
$this->db->limit($limit);
$query = $this->db->get();
return $query->result_array();
}
//get all message
function getAll() {
$query = $this->db->get('tb_chat');
return $query->result_array();
}
}
view: index.php
<!DOCTYPE html>
<html>
<head>
<title>chat room</title>
<meta charset="utf-8">
<script src="common/js/jquery.min.js"></script>
<style>
body {
padding:0px 50px;
}
#content {
border: 1px solid #ccc;
height: 400px;
overflow: auto;
}
#form {
border: 1px solid #ccc;
}
</style>
</head>
<body onload="get();">
<div id="content">
</div>
<hr>
<div id="form">
<form id="chat_form">
<table>
<tr>
<td>
我是:<input type="text" id="username" name="username">
</td>
<td>
發言:
<textarea id="textarea" rows="5" cols="50"></textarea>
</td>
<td><input id="sendBtn" type="button" value="發送" onclick="send();"></td>
</tr>
</table>
</form>
<hr>
<?php echo anchor('index/more', '查看全部聊天記錄'); ?>
</div>
</body>
<script>
function check() {
var textareaValue = document.getElementById('textarea').value;
if (textareaValue == '') {
alert('啥都沒有,就不用發送啦~');
return false;
}
return true;
}
function send() {
if (check() == false) return false;
var username = $('#username').val();
var content = $('#textarea').val();
var url = 'index.php/index/send';
if ($('#sendBtn').val() == '發送中...') return false;
$('#sendBtn').val('發送中...');
$.post(url, {'username':username,'content':content},function(result){
if (result == 0)
alert('send false');
else
$('textarea').val('');
$('#sendBtn').val('發送');
});
}
$(document).ready(function(){
var timer = setInterval('get()', 5000);//5秒自動獲取一次最新消息
});
function get() {
var url = 'index.php/index/show';
$.post(url,function(result){
$('#content').replaceWith(result);
})
}
</script>
</html>
view: more.php<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>All message</title>
</head>
<body style="padding: 0px 50px;">
<div style="border: 1px solid #ccc;">
<?php foreach($content as $item): ?>
<p>
<?php echo $item['username']; ?> [<?php echo $item['send_date']; ?>]:<br>
<?php echo $item['content']; ?>
</p>
<hr>
<?php endforeach; ?>
<p style="text-align: right; padding-right: 100px;"><a href="<?php echo $base_url; ?>">Return</a></p>
</div>
</body>
</html>
view: show.php<div id="content">
<?php foreach($content as $item): ?>
<p>
<?php echo $item['username']; ?> [<?php echo $item['send_date']; ?>]: <?php echo $item['content']; ?>
</p>
<hr>
<?php endforeach; ?>
</div>
SQL: chat.sql
--
-- 表的結構 `tb_chat`
--
CREATE TABLE IF NOT EXISTS `tb_chat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`content` text NOT NULL,
`send_date` datetime NOT NULL,
`ip` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
注:其中有一問題,若一條message內容過多,或者顯示太多的message,div會顯示一個滾動條,但是滾動條不能自動到底。