一些基礎(chǔ)知識(shí):
首先了解XMLHttpRequest對(duì)象的屬性和方法:
關(guān)于Ajax的示例:
一:
創(chuàng)建一個(gè)XMLHttpRequest對(duì)象
//創(chuàng)建ajax引擎對(duì)象
function createAjaxObject(){
if(window.ActiveXObject){
var newRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else{
var newRequest = new XMLHttpRequest();
}
return newRequest;
}
創(chuàng)建對(duì)象:
var http_request = createAjaxObject();//①創(chuàng)建一個(gè)XMLHttpRequest對(duì)象
二:創(chuàng)建url,data,通過(guò) xmlHttpRequest.send()
if(http_request){
var url = "sendmes.php";//通過(guò)myXmlHttpRequest對(duì)象發(fā)送請(qǐng)求到服務(wù)器的某個(gè)頁(yè)面
var sender = "<?php echo $nickname; ?>";
var geter = "<?php echo $geter; ?>";
var content = $("#sendBox").val();//頁(yè)面抓取的值
var data = "content="+content+"&sender="+sender+"&geter="+geter;
三:打開(kāi)請(qǐng)求
http_request.open("post",url,true);
//第一個(gè)參數(shù)表示請(qǐng)求的方式, "get" / "post"http://第二個(gè)參數(shù)指定url,對(duì)哪個(gè)頁(yè)面發(fā)出ajax請(qǐng)求(本質(zhì)仍然是http請(qǐng)求)
//第三個(gè)參數(shù)表示 true表示使用異步機(jī)制,如果false表示不使用異步
1使用GET的話使用get方式發(fā)出請(qǐng)求,如果提交的用戶名不變化靶壮,瀏覽器將不會(huì)真的發(fā)請(qǐng)求辜限,而是緩存取數(shù)據(jù)
url="/ajax/registerProcess.php?mytime="+new Date()+"&username="+$("username").value;
或:告訴瀏覽器不要緩存數(shù)據(jù)//header("Cache-Control: no-cache")
若瀏覽器返回的數(shù)據(jù)是xml格式
//header("Content-Type: text/xml;charset=utf-8");
***還有一句話帆调,這句話必須.用JSON提交//POST方式交互所需要增加的代碼
http_request.setRequestHeader("content-type","application/x-www-form-urlencoded");
四:指定回調(diào)函數(shù):注冊(cè)回調(diào)方法
//指定回調(diào)函數(shù).
http_request.onreadystatechange = function(){
if(http_request.readyState==4){
//等于200表示成功
if(http_request.status==200){
var res = http_request.responseText;
if(res!=""){
//res==""說(shuō)明發(fā)送成功,然后就將發(fā)送信息寫(xiě)入messageBox
//var nowtime = new Date().toLocaleString();
var content1 = "<?php echo $nickname.' '; ?>"+res+"\r\n";
var content2 = content+"\r\n" ;
var contents = $("#messageBox").val()+content1+content2;
//alert(content);
$("#messageBox").val(contents);
$("#sendBox").val(""); //將發(fā)送框清除
}
}
}
}
設(shè)置向服務(wù)器端發(fā)送的數(shù)據(jù)癣漆,啟動(dòng)和服務(wù)器端的交互
//真的發(fā)送請(qǐng)求,如果是get請(qǐng)求則填入 null即可
//如果是post請(qǐng)求,則填入實(shí)際的數(shù)據(jù)
http_request.send(data);
五:服務(wù)器端接收 ajax的請(qǐng)求,做相應(yīng)處理(操作數(shù)據(jù)庫(kù)),然后返回結(jié)果(echo 語(yǔ)句)
六:客戶端通過(guò)xmlHttpRequest的屬性 reponseText , responseXML 取的數(shù)據(jù)约炎,然后就完成局部刷新當(dāng)前頁(yè)面任務(wù)
示例:
<?php
session_start();
include "include/dbconn.php";
include "include/common.inc.php";
$geter= $_GET['geter'];
$nickname = $_SESSION['nickname'];
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/main.css" type="text/css" rel="stylesheet" />
<title>web聊天</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
//創(chuàng)建ajax引擎對(duì)象
function createAjaxObject(){
if(window.ActiveXObject){
var newRequest = new ActiveXObject("Microsoft.XMLHTTP");
}else{
var newRequest = new XMLHttpRequest();
}
return newRequest;
}
//定義全局變量 http_request
var http_request;
//**********************發(fā)送消息******************
$(function(){
$("#sendmess").click(sendMessage);
});
function sendMessage(){
var http_request = createAjaxObject();//①創(chuàng)建一個(gè)XMLHttpRequest對(duì)象
if(http_request){
//②創(chuàng)建url,data,通過(guò) xmlHttpRequest.send()
//③服務(wù)器端接收 ajax的請(qǐng)求,做相應(yīng)處理(操作數(shù)據(jù)庫(kù)),然后返回結(jié)果(echo 語(yǔ)句)
//④客戶端通過(guò)xmlHttpRequest的屬性 reponseText , responseXML 取的數(shù)據(jù),然后就完成局部刷新當(dāng)前頁(yè)面任務(wù)
var url = "sendmes.php";//通過(guò)myXmlHttpRequest對(duì)象發(fā)送請(qǐng)求到服務(wù)器的某個(gè)頁(yè)面
var sender = "<?php echo $nickname; ?>";
var geter = "<?php echo $geter; ?>";
var content = $("#sendBox").val();
var data = "content="+content+"&sender="+sender+"&geter="+geter;
//alert(data);
////打開(kāi)請(qǐng)求
///使用GET的話使用get方式發(fā)出請(qǐng)求圾浅,如果提交的用戶名不變化掠手,瀏覽器將不會(huì)真的發(fā)請(qǐng)求,而是緩存取數(shù)據(jù)., url
//url="/ajax/registerProcess.php?mytime="+new Date()+"&username="+$("username").value;
////這里兩句話很重要,第一講話告訴瀏覽器返回的數(shù)據(jù)是xml格式
//header("Content-Type: text/xml;charset=utf-8");
//告訴瀏覽器不要緩存數(shù)據(jù)
//header("Cache-Control: no-cache")
http_request.open("post",url,true);
//第一個(gè)參數(shù)表示請(qǐng)求的方式, "get" / "post"http://第二個(gè)參數(shù)指定url,對(duì)哪個(gè)頁(yè)面發(fā)出ajax請(qǐng)求(本質(zhì)仍然是http請(qǐng)求)
//第三個(gè)參數(shù)表示 true表示使用異步機(jī)制,如果false表示不使用異步
////還有一句話狸捕,這句話必須.用JSON提交//POST方式交互所需要增加的代碼
http_request.setRequestHeader("content-type","application/x-www-form-urlencoded");
//指定回調(diào)函數(shù).chuli是函數(shù)名
http_request.onreadystatechange = function(){
if(http_request.readyState==4){
//等于200表示成功
if(http_request.status==200){
var res = http_request.responseText;
if(res!=""){
//res==""說(shuō)明發(fā)送成功喷鸽,然后就將發(fā)送信息寫(xiě)入messageBox
//var nowtime = new Date().toLocaleString();
var content1 = "<?php echo $nickname.' '; ?>"+res+"\r\n";
var content2 = content+"\r\n" ;
var contents = $("#messageBox").val()+content1+content2;
//alert(content);
$("#messageBox").val(contents);
$("#sendBox").val(""); //將發(fā)送框清除
}
}
}
}
//真的發(fā)送請(qǐng)求,如果是get請(qǐng)求則填入 null即可
//如果是post請(qǐng)求,則填入實(shí)際的數(shù)據(jù)
http_request.send(data);
}
}
//**********************接收消息**************
setInterval(getMessage,1000); //每1秒發(fā)送一次請(qǐng)求
function getMessage(){
var http_request = createAjaxObject();
if(http_request){
var url = "getmes.php";
var sender = "<?php echo $nickname; ?>";
var geter = "<?php echo $geter; ?>";
var data = "sender="+sender+"&geter="+geter;
//alert(data);
http_request.open("post",url,true);
http_request.setRequestHeader("content-type","application/x-www-form-urlencoded");
http_request.onreadystatechange = function(){
if(http_request.readyState==4){
//等于200表示成功
if(http_request.status==200){
if(http_request.responseText=="nomessage"){return;}
//轉(zhuǎn)成對(duì)象數(shù)組//通過(guò)reses可以取得你希望的任何一個(gè)值reses[?].屬性名
var res = eval("("+http_request.responseText+")");
for(var i=0;i<res.length;i++){
var content1 = "<?php echo $geter; ?> "+res[i].stime+"\r\n";
var content2 = res[i].content+"\r\n" ;
var contents = $("#messageBox").val()+content1+content2;
//alert(content);
$("#messageBox").val(contents);
}
}
}
}
http_request.send(data);
}
}
</script>
</head>
<body>
<?php
if(empty($_SESSION['password'])){
echo "<a href='login.php'>登陸</a> <a href='regist.php' target='_blank'>注冊(cè)</a>";
exit();
}else{
echo $nickname. " 在線 <a href='exit.php'>退出登陸</a>";
}
?>
<div id="message">
<hr />
<p>與<font color='red'> <?php echo $geter; ?> </font>聊天中</p>
<hr />
<textarea readonly="readonly" id="messageBox"></textarea>
</div>
<div id="message2">
<textarea name="content" id="sendBox"></textarea>
<p><input type="button" value="發(fā)送" id="sendmess" /></p>
</div>
</body>
</html>
sendmes.php:
<?php
//這里兩句話很重要,第一講話告訴瀏覽器返回的數(shù)據(jù)是xml格式
//header("Content-Type: text/xml;charset=utf-8");
header("Content-type:text/html;charset=utf-8");//JSON
//告訴瀏覽器不要緩存數(shù)據(jù)
header("Cache-Control: no-cache");
if(empty($_POST['sender'])){exit();}
$sender = $_POST['sender'];
$geter = $_POST['geter'];
$content = $_POST['content'];
//$aa = $content."&".$sender."&".$geter;
//file_put_contents("log.txt",$content."\r\n",FILE_APPEND);
include "include/dbconn.php";
$sql = "INSERT INTO message (sender,geter,content,stime)VALUES ('{$sender}','{$geter}','{$content}',now())";
//file_put_contents("log.txt",$sql."\r\n",FILE_APPEND);
$res = mysql_query($sql,$link);
if(!$res){
echo ""; //發(fā)送失敗
}else{
date_default_timezone_set("PRC");
echo date("H:i:s");
}
?>
getmes.php
<?php
header("Content-type:text/html;charset=utf-8");
if(empty($_POST['sender'])){exit();}
$sender = $_POST['sender'];
$geter = $_POST['geter'];
include "include/dbconn.php";
$sql = "select content,stime from message where sender='{$geter}' and geter='{$sender}' and mloop=0 order by stime asc";
//file_put_contents("log.txt",$sql."\r\n",FILE_APPEND);
$res = mysql_query($sql,$link);
$row=mysql_fetch_array($res);
//消息條數(shù) 采用json返回?cái)?shù)據(jù)
$mNums = mysql_num_rows($res);
if($mNums<1){
echo "nomessage";
exit();
}else if($mNums==1){
echo "[{'content':'".$row['content']."','stime':'".substr($row['stime'],11)."'}]";
}else{
$result="[{'content':'".$row['content']."','stime':'".substr($row['stime'],11)."'}";
while($row=mysql_fetch_array($res)){
$result.=",{'content':'".$row['content']."','stime':'".substr($row['stime'],11)."'}";
}
$result.=']';
echo $result;
}
mysql_free_result($res);
//收到消息后將它的狀態(tài)設(shè)為1
if($mNums>0){
$sql = "update message set mloop=1 where sender='{$geter}' and geter='{$sender}' and mloop=0";
mysql_query($sql,$link);
//file_put_contents("log.txt",$sql."\r\n",FILE_APPEND);
}
?>