DIV CSS 佈局教程網

PHP + Ajax 實作無刷新發表評論的完整流程
編輯:AJAX基礎知識     

大家都有在網站發表評論的經驗,傳統流程是:填寫 → 送出表單 → 等頁面刷新。網路擁擠時,這段等待特別漫長。本文用 PHP 加 Ajax 做到無刷新發表評論,希望對剛入門 Ajax 的 PHPer 有幫助。

一、ajax.js:可重複使用的請求框架

先準備一個基本的 Ajax 開發框架。這支檔案包含三部分:send_request 負責建立物件並送出請求,processrequest 處理回應,checkfourm 做前端驗證並觸發送出。

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

流程很清楚:按下發表後,先在指定位置顯示「正在發送數據...」,接著送出請求,由回呼函式把伺服器回應填回同一個容器。

二、伺服器端:sendnewfourm.php

<?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>";
$db->close();
?>

開頭那句 header 很重要:JavaScript 採 UTF-8 編碼,在 Windows 環境下若伺服器輸出未標明 GMT2312,Ajax 取回中文就會亂碼。中間兩個 include 分別是資料庫操作類與設定檔——我習慣把基本的資料庫操作寫成一個類,日後呼叫方便。

三、頁面 HTML

評論列表用隱藏的 IFRAME 載入,資訊送出後只刷新這個框架,就能看到新留言,全程不必重整整個頁面:

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td align="center"><?php echo $rows_p[p_info]; ?></td>
  </tr>
  <tr>
    <td align="center"><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 align="center"><br><br>
      <div align="center" id="result"></div>
      <form name="fourm">
      <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
          <td height="25">&nbsp;快速發表評論
            <span class="STYLE1">(必須先登陸)用戶名:
              <input name="username" type="text" value="<?=$username?>" readonly>
            </span>
          </td>
        </tr>
        <tr>
          <td height="32" align="center" valign="middle">
            <textarea name="newfourm" class="f" id="newfourm"></textarea>
          </td>
        </tr>
        <tr>
          <td height="32">&nbsp;
            <input name="submit" type="button" value="發表評論" onClick="checkfourm('result')">
            <input name="reset" type="reset" id="reset" value="重新填寫">
            <input name="id" type="hidden" id="id" value="<?php echo "$id"; ?>">
          </td>
        </tr>
      </table>
      </form>
    </td>
  </tr>
</table>

四、操作流程

1. 按下「發表評論」,開始送出資料。

點擊提交後開始發送數據

2. 資料送出成功,容器內顯示成功提示。

數據發送成功

3. 刷新評論列表,只更新 IFRAME 區域。

刷新評論列表

五、這份程式碼值得留意的三個問題

一、reobj 是全域變數。processrequest 透過它決定要把結果寫到哪個容器,但 send_request 與 checkfourm 之間靠隱含的全域狀態溝通,一旦同頁有多個表單就會互相干擾。較穩妥的做法是把目標元素 id 一起當參數傳入,或改用回呼函式。

二、SQL 直接拼接使用者輸入。sendnewfourm.php 把 $newfourm 與 $username 直接放進 insert 陳述式,這是典型的 SQL injection 弱點。應改用 prepared statement 綁定參數,同時對輸出內容做轉義,避免 XSS。

三、GET 傳送評論內容。以 GET 送出文字會讓內容暴露在網址列與伺服器日誌中,且有長度限制。改成 POST 更合適,伺服器端相應改用 $_POST 取值。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved