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

[size=medium][b]概览[/b][/size]

[img]http://dl2.iteye.com/upload/attachment/0121/0919/d7500f07-ec5c-3a56-824e-89fb5b62c74d.png[/img]

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


[size=medium][b]一、搭建聊天页面[/b][/size]



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





[size=medium][b]二、css 样式[/b][/size]



/* 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; }





[size=medium][b]三、使用 PHP 创建登录页面[/b][/size]

[img]http://dl2.iteye.com/upload/attachment/0121/0945/3ad0d89d-bac4-3ddb-83e4-89c7aa1a7cb3.png[/img]



<?
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))。


[b]调转至登录页面[/b]

如果用户没登录,则 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
}
?>




[b]欢迎和注销[/b]

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

1、把用户名显示出来:


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


[img]http://dl2.iteye.com/upload/attachment/0121/0947/b40ba61d-f7d1-3137-98ca-71f7c1a6242b.png[/img]


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


[img]http://dl2.iteye.com/upload/attachment/0121/0950/d7655602-c210-3c8e-b2b1-a1f73d9206a7.png[/img]

我们需要使用 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
}




[size=medium][b]四、处理用户的输入[/b][/size]

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

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 文件中。


[size=medium][b]五、展示聊天记录的内容(log.html)[/b][/size]

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


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 > 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 秒钟从新加载用户聊天记录文件。


[b]更多阅读:[/b]


[url=http://net.tutsplus.com/tutorials/php/secure-your-forms-with-form-keys]Secure Your Forms With Form Keys[/url] - prevent prevent XSS (Cross-site scripting) and Cross-site request forgery

[url=http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery]Submit A Form Without Page Refresh using jQuery[/url] - Expand on our ajax request

[url=http://net.tutsplus.com/videos/screencasts/how-to-make-ajax-requests-with-raw-javascript]How to Make AJAX Requests With Raw Javascript[/url] - 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


-
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值