DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
用 AJAX 實現評論的無刷新提交
編輯:AJAX詳解     

評論提交是 AJAX 的經典應用場景。通過異步提交,用戶無需刷新頁面即可看到最新評論,配合一個「加載中」的提示層,體驗會更加流暢。下面是完整的實現代碼。

加載提示層

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; font-family:Arial; color:#660000; background:#222; opacity:.7; filter:alpha(opacity=70); display:none;"><br/><font color="#FF6600"><strong>數據正在讀取中,請等候...</strong></font><br/><img src="https://www.pushad.com/Info/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 對象

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

讀取與提交數據

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()
            }
        }
    }
}

字符串去空格與表單提交

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

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; }
        else { 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 編碼 → 以 POST 異步提交 → 提交成功後重新拉取最新評論列表,並在兩秒後清空提示信息。配合居中的加載動畫,用戶在等待期間能獲得清晰的視覺反饋。

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