하나의 로그 파일 만 사용하는 대화방 응용 프로그램 (예 : 사이트의 모든 사용자가 같은 방에 로그인 한 경우)을 사용하려는 경우 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>
가, 다음, 당신은 완벽하게 사용자 입력에 소요 뭔가를해야합니다, 사용자가 텍스트 상자에 입력하고 전송 어떤 : 해당위한 양식이 필요합니다 아약스는 어디에서 오는 스크립트에, 그건 :이 작업을 수행 한 후
<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는 특정 시간 후에 파일을 다시로드하는 데 사용됩니다. R의이 포함 된 어떤 메시지와 함께 속도까지 항상, 여기에 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>
이 부문의 그 : 당신이 로그인 시스템이 파일에 데이터를 작성 후, 어쨌든,이에 딱 맞는 방법을 볼 수 있는지 로그 도저히 안 믿기는, 우리는 사용자가 볼 수 있도록 업로드해야 이제 로그 파일을로드 할 위치가 남아 있습니다. 일정 시간이 지나면 파일을 다시로드하고 자동 스크롤 기능을 추가해야합니다.
//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
그리고 이것이 도움이 될 것입니다. 유용한 답을 얻지 못했다면 도움이되기를 바랍니다. 오랜 시간 기다려야 할 것입니다.
안녕하세요! 전통적인 대답은 Ajax (Asynchronous Javascript)입니다. interwebs에는 문자 그대로 수천 개의 Ajaxified PHP chatroom 튜토리얼이 있습니다. 앞으로는 웹 소켓이 대신되지만 그 날은 아직 여기에 없습니다. –
실시간 채팅은 엔지니어가 구현하는 복잡한 시스템입니다. 특히 기본 기술이 어떻게 작동하는지 잘 이해하지 못하는 경우가 많습니다. 가장 좋은 조언은 통합 할 준비가 된 제 3 자 채팅 시스템을 검색하는 것입니다. –
php + js가이 작업에 가장 적합한 스택이 아닙니다. [node.js + js] (http://chat.nodejs.org/)입니다. – moonwave99