我正在尝试创建一个简单的 AJAX/PHP 聊天应用程序,以实现网站上注册用户之间的通信。它的问题是存储聊天记录。我曾想过将所有聊天消息存储在一个数据库中(包含 user1、user2、message、time 等列),然后在每次 AJAX 请求时,在数据库中搜索用户之间的匹配消息,但我认为这可能非常效率低下。以这种方式实现它是一个好主意,有什么好的方法来处理它?
问问题
1650 次
2 回答
1
由于聊天室必须不断获得更新,我想将请求降到最低,所以我只是用数据库 ID 标记了每条消息。由于每个用户都可以看到该房间的所有消息,因此请求只是将 id 发送到服务器以查看是否有任何新帖子。如果有,它会返回新帖子并更新页面。
这是我使用的 JavaScript:
var csrf = $("input[name='csrf_test_name']").val();
load_messages();
load_users();
$("#submitbutton").click(function(){
var message = $("#content").val();
$.post(base_url + "index.php/chat/ajax_post", {
text: message,
csrf_test_name: csrf
});
$("#content").attr("value", "");
return false;
});
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "index.php/chat/ajax_retrieve",
type: "POST",
data: {
last: last,
csrf_test_name: csrf
},
cache: false,
success: function(html){
if(html.substr(1, 1) == 'p'){
var oldscrollHeight = $("#messagewindow").prop("scrollHeight") - 20;
var id;
var tag;
var user;
var uid;
//remove messages that exceed the max - determined on the server side
$('#messagewindow p:lt(' + $(html).siblings().size() + ')').remove();
//add messages, emoticons and classes based on whether its the user or someone else
$(html).find('b').each(function(){
if ($(this).html() == user_name + ':'){
$('#messagewindow').append($(this).parent().emoticons(base_url + 'images/emoticons').attr('class', 'self'));
} else {
$('#messagewindow').append($(this).parent().emoticons(base_url + 'images/emoticons').attr('class', 'others'));
}
});
//scroll screen
var newscrollHeight = $("#messagewindow").prop("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#messagewindow").animate({ scrollTop: newscrollHeight }, 'normal');
}
$(html).find('span').each(function(){
id = $(this).attr('id');
uid = 'u' + id.substr(1);
if (id.substr(0, 1) == 'e' && $('#userwindow p[id="' + uid + '"]').size() < 1){
user = $(this).prev().html();
tag = "<p id='" + uid + "'>" + user.substr(0, user.length - 1) + "</p>";
$('#userwindow').append(tag);
} else if(id.substr(0, 1) == 'x') {
$('#userwindow p[id="u' + id.substr(1) + '"]').remove();
}
});
}
}
});
}
function load_users(){
$.ajax({
url: base_url + "index.php/chat/ajax_users",
cache: false,
success: function(html){
if(html.substr(1, 1) == 'p'){
$("#userwindow").html(html);
}
}
});
}
setInterval(load_messages, 2000);
setInterval(load_users, 240000);
于 2013-05-11T18:40:42.710 回答
0
你的方法会有什么问题?
在您的表上使用正确的 MySQL 索引(我会说在两列user1
以及user2
时间戳或订单的唯一 ID 上),性能将足够好。
您可以将当前时间戳添加到 AJAX 请求中,以仅检索您之前未加载调用的消息。
于 2013-05-11T17:15:18.017 回答