本文示範如何以 jQuery 為 WordPress 的留言功能加上 AJAX 效果,讓留言送出後無需刷新即可看到結果,並搭配載入動畫與淡出淡入過場。

這一步並非絕對必要,但建議把留言表單的 id 設為 #commentform、留言清單設為 #commentlist,並視情況新增 #commentload(顯示提交狀態)與 #commenterror(顯示錯誤)兩個 span,再用一個 #commentformbox 的 div 把表單包起來。這些命名是為了迎合下面的 jQuery 腳本。
利用 jQuery 的 ajax() API,攔截表單提交,成功後把新留言附加到清單,並在 15 秒後才允許再次留言,以避免洗版:
if ($('#commentform').length) {
$('#commentform').submit(function(){
jQuery.ajax({
url: 'comments-ajax.php',
data: $('#commentform').serialize(),
type: 'POST',
beforeSend: function() {
$('#commenterror').hide();
$('#commentload').show();
},
error: function(request) {
$('#commentload').hide();
$('#commenterror').show().html(request.responseText);
},
success: function (data) {
$('textarea').each(function(){ this.value=''; });
$('#commenterror').hide().html();
$('#comments').html(parseInt($('#comments').html()) + 1);
if (!$('#commentlist').length) {
$('#pinglist').before('<ul id="commentlist"></ul>');
}
$('#commentlist').append(data);
$('#commentform :input').attr('disabled', true);
$('#commentformbox').fadeOut(1000);
$('#commentload').hide();
setTimeout(function() {
$('#commentform :input').removeAttr('disabled');
$('#commentformbox').fadeIn(1000);
}, 15000);
}
});
return false;
});
}這個檔案負責把表單資料寫入 WordPress 資料庫,並回傳一筆留言的 li 元素。核心流程包括:確認請求為 POST、載入 wp-config.php、檢查文章狀態與留言是否開放、驗證必填欄位與電子郵件、進行重複留言檢查,最後呼叫 wp_new_comment() 寫入並輸出對應的 li 標記(其中的 li 結構需依你的 comments.php 調整)。
把這些檔案放進目前主題目錄,並在 header.php 中引入 jQuery 與 comments.js。重新載入網站後留言,即可看到 AJAX 化的效果:提交後表單框淡出、15 秒後淡入。若想要「正在提交」的旋轉動畫,可把 spinner.gif 放進 images 目錄,並在 style.css 加上:
#commentload {
display: none; height: 18px; width: 18px;
background: url('images/spinner.gif') no-repeat center center;
}若覺得預設動畫不夠好看,也可到 ajaxload.info 產生自己喜歡的載入圖示。