Web サイトで登録ユーザー間の通信を可能にする単純な AJAX/PHP チャット アプリケーションを作成しようとしています。問題はチャット履歴の保存です。すべてのチャット メッセージを 1 つのデータベース (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 インデックスを使用すると (2 つの列と、注文のタイムスタンプまたは一意の ID で言うと思いますuser1
) user2
、パフォーマンスは十分に良好です。
現在のタイムスタンプを AJAX リクエストに追加して、以前に呼び出しをロードしていないメッセージのみを取得できます。
于 2013-05-11T17:15:18.017 に答える