DIV CSS 佈局教程網

Ajax 實作評論提交:從載入動畫到表單驗證
編輯:AJAX基礎知識     

用 Ajax 做評論提交,真正花心思的往往不是「送出」這一步,而是送出前後的那些細節:使用者按下送出之後有沒有回饋?驗證碼忘了填會不會直接白跑一趟?成功之後頁面要不要自動刷新?下面這份腳本把這些環節都收攏在一起。

先準備一個載入提示

請求還在飛行中時,畫面不能是一片死寂。範例用 document.write 動態插入一個半透明的浮層,置中顯示「數據正在讀取中,請等候」與一張 loading 動圖,並透過 showloading() 反覆切換顯示狀態。

document.write('<div id="loadingg" style="height:65px;width:205px;position:absolute;z-index:1000;
border:3px #fff solid;text-align:center;font-size:12px;color:#660000;background:#222;
opacity:.7;-moz-opacity:.7;filter:alpha(opacity=70);display:none;">
<br/><font color="#FF6600"><strong>數據正在讀取中,請等候...</strong></font><br/>
<img src="images/loading.gif"/></div>')

function showloading() {
  var obj = document.getElementById("loadingg");
  if (obj.style.display != "") {
    obj.style.left = ((document.documentElement.clientWidth - parseFloat(obj.style.width)) / 2)
                     + document.documentElement.scrollLeft + "px";
    obj.style.top  = ((document.documentElement.clientHeight - parseFloat(obj.style.height)) / 2)
                     + document.documentElement.scrollTop + "px";
    obj.style.display = "";
  } else {
    obj.style.display = "none";
  }
}

幾個萬用的小工具

後續程式碼大量用到這幾支短函式,先寫成一行,整份腳本立刻清爽許多:

function $(id) { return document.getElementById(id); }
function echo(obj, html) { $(obj).innerHTML = html; }
function fopen(obj)  { $(obj).style.display = ""; }
function fclose(obj) { $(obj).style.display = "none"; }

建立 XMLHTTP 物件

跨瀏覽器的老問題。先試 IE 的 ActiveX 寫法(含 Msxml2 與 Microsoft 兩個版本),失敗再退回原生 XMLHttpRequest。

function createxmlhttp() {
  var xmlhttp = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) {
    try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) { xmlhttp = false; }
  }
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    xmlhttp = new XMLHttpRequest();
    if (xmlhttp.overrideMimeType) xmlhttp.overrideMimeType('text/xml');
  }
  return xmlhttp;
}

讀取與送出

讀取用 GET,把回應寫進指定的容器;送出用 POST,需要明確設定 Content-Type 為 application/x-www-form-urlencoded,並在成功後重新抓一次資料、清空輸入框、兩秒後收起提示。

function getdata(url, obj1, obj2) {
  var xmlhttp = createxmlhttp();
  if (!xmlhttp) { alert("你的瀏覽器不支持XMLHTTP!!"); return; }
  showloading();
  xmlhttp.onreadystatechange = requestdata;
  xmlhttp.open("GET", url, true);
  xmlhttp.send(null);

  function requestdata() {
    fopen(obj1);
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
        if (obj1 != obj2) fclose(obj1);
        echo(obj2, xmlhttp.responseText);
        showloading();
      }
    }
  }
}

function postdata(url, obj, data) {
  var rnd = Math.random();
  var xmlhttp = createxmlhttp();
  if (!xmlhttp) { alert("你的瀏覽器不支持XMLHTTP!!"); return; }
  showloading();
  xmlhttp.open("POST", url, true);
  xmlhttp.onreadystatechange = requestdata;
  xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlhttp.send(data);

  function requestdata() {
    fopen(obj);
    echo(obj, "正在提交數據,請稍等......");
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
        echo(obj, xmlhttp.responseText);
        reget(rnd);
        setTimeout("echo('showresult','')", 2000);
        echo('Message', '');
        showloading();
      }
    }
  }
}

去空格與表單取值

使用者輸入難免多打空白,因此自製 lTrim、rTrim 以遞迴方式剝除左右空白,再包成 trim;取值則統一走 f(),省得每次都要寫 document.ajax_post.xxx.value。

function lTrim(str) {
  if (str.charAt(0) == " ") { str = str.slice(1); str = lTrim(str); }
  return str;
}
function rTrim(str) {
  var iLength = str.length;
  if (str.charAt(iLength - 1) == " ") { str = str.slice(0, iLength - 1); str = rTrim(str); }
  return str;
}
function trim(str) { return lTrim(rTrim(str)); }
function f(obj) { return trim(eval("document.ajax_post." + obj + ".value")); }

送出前的驗證

SaveReply() 是總入口,依序檢查用戶名與內容不可為空,再按表單上勾選框的狀態決定要不要帶上驗證碼、密碼等欄位,最後把所有值 escape 後拼成查詢字串交給 postdata。

function SaveReply() {
  if (f("username") == "") { alert("請填寫用戶名"); return false; }
  if (f("Message")  == "") { alert("內容不可為空"); return false; }

  var validate, password, log_DisKey = 0, log_DisURL = 0, log_DisSM = 0;
  validate = ""; password = "";

  if (document.ajax_post.log_DisKey.checked) log_DisKey = f("log_DisKey");
  if (document.ajax_post.log_DisURL.checked) log_DisURL = f("log_DisURL");
  if (document.ajax_post.log_DisSM.checked)   log_DisSM   = f("log_DisSM");

  if ((typeof eval(document.ajax_post.validate)) != "undefined") {
    if (f("validate") == "") { alert("請填寫驗證碼"); return false; }
    validate = f("validate");
  }
  if ((typeof eval(document.ajax_post.password)) != "undefined") password = f("password");

  data = "username="  + escape(f("username"))
       + "&password=" + escape(password)
       + "&validate=" + escape(validate)
       + "&log_DisSM=" + escape(log_DisSM)
       + "&log_DisURL=" + escape(log_DisURL)
       + "&log_DisKey=" + escape(log_DisKey)
       + "&Message="  + escape(f("Message"))
       + "&logID="     + escape(f("logID"))
       + "&action="   + escape(f("action"));

  postdata("wbc_blogcomm.asp", "showresult", data);
  return true;
}

幾個實務上的提醒

值得留意的是,escape 對中文字元的處理並不可靠,後端若採 GB2312 或 UTF-8,最好改用 encodeURIComponent 並在伺服器端對應解碼。另外,這裡的驗證只是前端攔截,真正的必填檢查、長度限制與驗證碼比對仍必須在伺服器端再做一次,否則繞過前端並不困難。最後,成功後的 reget(rnd) 帶著隨機參數重新拉取評論,是為了避開瀏覽器快取——這個小技巧在早期專案裡很常用,至今仍舊有效。

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