javascript之小应用:网页在线聊天

概览



这款使用 PHP 和 javascript 搭建的网页在线聊天程序包括:用户登录、注销、Ajax 功能 并且支持多用户。


一、搭建聊天页面


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Chat - Customer Module</title>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
 
<div id="wrapper">
    <div id="menu">
        <p class="welcome">Welcome, <b></b></p>
        <p class="logout"><a id="exit" href="#">Exit Chat</a></p>
        <div style="clear:both"></div>
    </div>
     
    <div id="chatbox"></div>
     
    <form name="message" action="">
        <input name="usermsg" type="text" id="usermsg" size="63" />
        <input name="submitmsg" type="submit"  id="submitmsg" value="Send" />
    </form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
 
});
</script>
</body>
</html>






二、css 样式


/* CSS Document */
body {
    font:12px arial;
    color: #222;
    text-align:center;
    padding:35px; }
  
form, p, span {
    margin:0;
    padding:0; }
  
input { font:12px arial; }
  
a {
    color:#0000FF;
    text-decoration:none; }
  
    a:hover { text-decoration:underline; }
  
#wrapper, #loginform {
    margin:0 auto;
    padding-bottom:25px;
    background:#EBF4FB;
    width:504px;
    border:1px solid #ACD8F0; }
  
#loginform { padding-top:18px; }
  
    #loginform p { margin: 5px; }
  
#chatbox {
    text-align:left;
    margin:0 auto;
    margin-bottom:25px;
    padding:10px;
    background:#fff;
    height:270px;
    width:430px;
    border:1px solid #ACD8F0;
    overflow:auto; }
  
#usermsg {
    width:395px;
    border:1px solid #ACD8F0; }
  
#submit { width: 60px; }
  
.error { color: #ff0000; }
  
#menu { padding:12.5px 25px 12.5px 25px; }
  
.welcome { float:left; }
  
.logout { float:right; }
  
.msgln { margin:0 0 2px 0; }






三、使用 PHP 创建登录页面




<?
session_start();
 
function loginForm(){
    echo'
    <div id="loginform">
    <form action="index.php" method="post">
        <p>Please enter your name to continue:</p>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" />
        <input type="submit" name="enter" id="enter" value="Enter" />
    </form>
    </div>
    ';
}
 
if(isset($_POST['enter'])){
    if($_POST['name'] != ""){
        $_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
    }
    else{
        echo '<span class="error">Please type in a name</span>';
    }
}
?>




该登录页面要求用户输入用户名,使用if else 语句判断是否用户输入了用户名。
如果输入了用户名,则将其存入session中:$_SESSION['name']

特别说明一点是:我们使用了 htmlspecialchars() 函数,将 HTML 字符转换为其字符本身,以防止用户输入恶意的代码( Cross-site scripting (XSS))。


调转至登录页面

如果用户没登录,则 session 不会被创建。所以我们使用 if else 语句进行判断:


<?php
if(!isset($_SESSION['name'])){
    loginForm();
}
else{
?>
<div id="wrapper">
    <div id="menu">
        <p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>
        <p class="logout"><a id="exit" href="#">Exit Chat</a></p>
        <div style="clear:both"></div>
    </div>    
    <div id="chatbox"></div>
     
    <form name="message" action="">
        <input name="usermsg" type="text" id="usermsg" size="63" />
        <input name="submitmsg" type="submit"  id="submitmsg" value="Send" />
    </form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
});
</script>
<?php
}
?>





欢迎和注销

我们尚未完成登录模块。应该允许用户注销和结束会话。
让我们在 Menu 菜单栏中增加一些 PHP 代码,以实现这个功能:

1、把用户名显示出来:

<p class="welcome">Welcome, <b><?php echo $_SESSION['name']; ?></b></p>





2、注销确认

使用 jQuery 完成用户注销时的确认窗口:


<script type="text/javascript">
// jQuery Document
$(document).ready(function(){
	//If user wants to end session
	$("#exit").click(function(){
		var exit = confirm("Are you sure you want to end the session?");
		if(exit==true){window.location = 'index.php?logout=true';}		
	});
});
</script>



如果用户点击确认注销,则网页会跳转至这个网址:index.php?logout=true




我们需要使用 php 获取注销页面传递过来的参数:

if(isset($_GET['logout'])){ 
     
    //before session destroy, simple exit message is written to a log file.
    $fp = fopen("log.html", 'a');
    fwrite($fp, "<div class='msgln'><i>User ". $_SESSION['name'] ." has left the chat session.</i><br></div>");
    fclose($fp);
     
    session_destroy();
    header("Location: index.php"); //Redirect the user
}




四、处理用户的输入

当用户点击发送按钮后,我们想获取用户的输入内容,并将其写入日志中。

1、使用 jQuery 获取用户的输入内容,并异步的发生post请求。


//If user submits the form
	$("#submitmsg").click(function(){	
		var clientmsg = $("#usermsg").val();
		$.post("post.php", {text: clientmsg});				
		$("#usermsg").attr("value", "");
		return false;
	});




2、使用 php 在服务器端接受请求,并获取用户发送的内容,将其写入日志文件中:

post.php


<?
session_start();
if(isset($_SESSION['name'])){
    $text = $_POST['text'];
     
    $fp = fopen("log.html", 'a');
    fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
    fclose($fp);
}
?>



我们将用户输入的信息都存储在 log.html 文件中。



五、展示聊天记录的内容(log.html)

向用户显示最近更新的聊天记录。


1、为了节省加载时间,可以提前将 log.html 加载:


<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>




2、使用  jQuery.ajax  发送请求:


//Load the file containing the chat log
function loadLog(){
    $.ajax({
        url: "log.html",
        cache: false,
        success: function(html){
            //Insert chat log into the #chatbox div
            $("#chatbox").html(html);		
        },
    });
}



让聊天记录可以滚动:


//Load the file containing the chat log
function loadLog(){
    //Scroll height before the request
    var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20; 
    $.ajax({
        url: "log.html",
        cache: false,
        success: function(html){
            //Insert chat log into the #chatbox div	
            $("#chatbox").html(html); 
            
            //Auto-scroll
            //Scroll height after the request
            var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20; 
            if(newscrollHeight &gt; oldscrollHeight){
                //Autoscroll to bottom of div
                $("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); 
            }				
        },
    });
}




3、实时更新聊天记录:


//Reload file every 2500 ms or x ms if you wish to change the second parameter

setInterval (loadLog, 2500);	



每 2.5 秒钟从新加载用户聊天记录文件。






更多阅读:


Secure Your Forms With Form Keys - prevent prevent XSS (Cross-site scripting) and Cross-site request forgery

Submit A Form Without Page Refresh using jQuery - Expand on our ajax request

How to Make AJAX Requests With Raw Javascript - Learn how  requests  work behind the scenes with raw javascript.





-

引用:

https://code.tutsplus.com/tutorials/how-to-create-a-simple-web-based-chat-application--net-5931




-
转载请注明:
原文出处:http://lixh1986.iteye.com/blog/2336028



-


猜你喜欢

转载自lixh1986.iteye.com/blog/2336028