大家都有在網站發表評論的經歷,傳統的發表過程無非是:發表->提交頁面表單->等待刷新頁面,這樣在網絡比較擁擠的時候,往往需要漫長的等待,今天介紹用PHP+Ajax實現頁面無刷新發表評論,希望對初學ajax的PHPer有所幫助。 那么首先,我們需要一個基本的ajax開發框架,文件ajax.js就包含了這個框架,代碼如下:
復制代碼 代碼如下:
var http_request=false;
function send_request(url){//初始化,指定處理函數,發送請求的函數
http_request=false;
//開始初始化XMLHttpRequest對象
if(window.XMLHttpRequest){//Mozilla瀏覽器
http_request=new XMLHttpRequest();
if(http_request.overrideMimeType){//設置MIME類別
http_request.overrideMimeType("text/xml");
}
}
else if(window.ActiveXObject){//IE瀏覽器
try{
http_request=new ActiveXObject("Msxml2.XMLHttp");
}catch(e){
try{
http_request=new ActiveXobject("Microsoft.XMLHttp");
}catch(e){}
}
}
if(!http_request){//異常,創建對象實例失敗
window.alert("創建XMLHttp對象失??!");
return false;
}
http_request.onreadystatechange=processrequest;
//確定發送請求方式,URL,及是否同步執行下段代碼
http_request.open("GET",url,true);
http_request.send(null);
}
//處理返回信息的函數
function processrequest(){
if(http_request.readyState==4){//判斷對象狀態
if(http_request.status==200){//信息已成功返回,開始處理信息
document.getElementById(reobj).innerHTML=http_request.responseText;
}
else{//頁面不正常
alert("您所請求的頁面不正常!");
}
}
}
function checkfourm(obj){
var f=document.fourm;
var newfourm=f.newfourm.value;
var username=f.username.value;
var id=f.id.value;
if(username==""){
document.getElementById(obj).innerHTML="<img src=images/false.gif> <font color=red>您必須先登錄!</font>";
return false;
}
else if(newfourm==""){
document.getElementById(obj).innerHTML="<img src=images/false.gif> <font color=red>您還沒填寫評論內容!</font>";
return false;
}
else{
document.getElementById(obj).innerHTML="正在發送數據...";
send_request('sendnewfourm.php?username='+username+'&newfourm='+newfourm+'&id='+id);
reobj=obj;
}
}
復制代碼 代碼如下:
<?php
header('Content-Type:text/html;charset=GB2312');//避免輸出中文亂碼,linux下不需要
$username=trim($_GET['username']);
$newfourm=trim($_GET['newfourm']);
$id=$_GET['id'];
$time=date("Y-m-d");
include('inc/config.inc.php');
include('inc/dbclass.php');
$db=new db;//從數據庫操作類生成實例
$db->mysql($dbhost,$dbuser,$dbpassword,$dbname);//調用連接參數函數
$db->createcon();//調用創建連接函數
$addsql="insert into cr_fourm values(0,'$newfourm','$username','$time',$id)";
$db->query($addsql);
echo"<img src=images/pass.gif> <font color=red>評論已成功發表!</font>";
//echo $addsql;
$db->close();//關閉數據庫連接
?>
復制代碼 代碼如下:
<table cellspacing="0" cellpadding="0">
<tr>
<td><?php echo $rows_p[p_info];?></td>
</tr>
<tr>
<td><br><br><iframe frameborder="0" scrolling="auto" src="showfourm.php?picid=<?=$id;?>" style=HEIGHT:250px;VISIBILITY:inherit;WIDTH:98%;Z-INDEX:2 ></iframe>
</td>
</tr>
<tr>
<td><br><br>
<div></div>
<form>
<table cellspacing="0" cellpadding="0">
<tr>
<td> 快速發表評論<span>(必須先登陸)用戶名:
<input type="text" value="<?=$username?>" readonly>
</span></td>
</tr>
<tr>
<td valign="middle"><textarea></textarea></td>
</tr>
<tr>
<td> <input type="button" value="發表評論">
<input type="reset" value="重新填寫">
<input type="hidden" value="<?php echo"$id";?>"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
新聞熱點
疑難解答
圖片精選