1 つのログ ファイルのみを使用するチャット ルーム アプリケーションを作成する場合、つまり、サイトの全員が同じルームにログインする場合、php と ajax と jquery を使用すればそれほど難しくありません。プロセスは次のとおりです。ユーザーにメッセージを入力して送信してもらいたいのですが、そのためのフォームが必要です。
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
これがフォームのマークアップです。次に、ユーザーがテキスト ボックスに入力した内容が何であれ、ユーザー入力をシームレスに取り込み、それをスクリプトに送信するものが必要になります。ここで ajax の出番です。
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript" >
//when the user clicks the button with the id submitmsg, the input is taken
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
//after the input's value is taken, it's sent to a script called
//pst.php
$.post("post.php", {text: clientmsg});
//after the message is sent, the input's value is set to null
//to allow the user to type a new message
$("#usermsg").attr("value", "");
return false;
});
</script>
これを行った後、スクリプト post.php がどのように見えるか、そしてそれが何をするかを確認する必要があります。その後、ユーザー間で送信されたメッセージを表示できます。さらに ajax を使用して、一定時間後にファイルをリロードし、ユーザーが含まれるメッセージに常に対応できるようにします。php スクリプトは次のとおりです。
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'><b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
私はセッションを使用したことに注意してください。これは、ログインしたユーザーの名前を取得し、それをログファイルに出力することです.データをファイルにアップロードするには、ユーザーが以下を確認できるようにアップロードする必要があります。
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?>
</div>
これはログ ファイルが読み込まれる部分です。あと 1 つだけ残っています。一定時間後にファイルをリロードし、自動スクロール機能を追加する必要があります。
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#inner").attr("scrollHeight") - 20;
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#inner").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#inner").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#inner").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2500); //Reload file every 2.5 seconds
これでうまくいくはずです。まだ有用な答えが得られていない場合に役立つことを願っています。長い間待っていたでしょう。