DIV CSS 佈局教程網

WordPress AJAX 評論提交實作示例
編輯:關於JavaScript     

WordPress 的 AJAX 評論提交可以在不重新載入整頁的情況下完成留言,提升使用者體驗,也能減少伺服器輸出整頁的負擔。

整體流程

前端攔截表單提交,將欄位資料以 POST 送到 WordPress。PHP 端驗證資料並寫入評論,成功後回傳新的評論 HTML,再由前端插入列表。

PHP 端

可在主題的 functions.php 中加入 AJAX 處理函式,接收 action、文章 ID、作者、信箱、網址與內容,進行基本驗證後寫入評論。

function fail($message) {
  header('HTTP/1.0 500 Internal Server Error');
  echo $message;
  exit;
}

function ajax_comment() {
  if ($_POST['action'] === 'ajax_comment') {
    $comment_post_ID = (int) $_POST['comment_post_ID'];
    $comment_author = trim(strip_tags($_POST['author']));
    $comment_author_email = trim($_POST['email']);
    $comment_author_url = trim($_POST['url']);
    $comment_content = trim($_POST['comment']);

    if ($comment_content === '') {
      fail('請輸入評論內容');
    }

    $comment_id = wp_new_comment(array(
      'comment_post_ID' => $comment_post_ID,
      'comment_author' => $comment_author,
      'comment_author_email' => $comment_author_email,
      'comment_author_url' => $comment_author_url,
      'comment_content' => $comment_content
    ));

    $comment = get_comment($comment_id);

    // 這裡輸出你的評論 HTML 結構
    die();
  }
}

add_action('init', 'ajax_comment');

正式環境建議加入 nonce 驗證、權限判斷與更完整的資料清理,避免惡意提交。

前端 JavaScript

使用 jQuery 攔截表單提交,將表單資料序列化後送到目前頁面網址,並在成功後把新評論插入列表。

jQuery('#commentform').submit(function () {
  var ajaxCommentsURL = window.location.href;

  jQuery.ajax({
    url: ajaxCommentsURL,
    data: jQuery('#commentform').serialize() + '&action=ajax_comment',
    type: 'POST',
    beforeSend: function () {
      jQuery('#commenterror').hide();
      jQuery('#commentload').fadeIn();
    },
    error: function (request) {
      jQuery('#commenterror').html(request.responseText);
      jQuery('#commentload').hide();
      jQuery('#commenterror').fadeIn();
    },
    success: function (data) {
      jQuery('textarea').each(function () {
        this.value = '';
      });

      jQuery('.commentlist li.comment').first().before(data);
      jQuery('#commentload').fadeOut(1600);
    }
  });

  return false;
});

CSS 提示

可為載入動畫與錯誤訊息加入樣式,讓回饋更清楚。

#commentload,
#commenterror {
  display: none;
  margin: 5px 0 0 0;
  color: #D29A04;
  font-size: 16px;
  padding: 0 0 0 20px;
}

AJAX 評論的重點不只是提交,也包括錯誤提示、重複提交防護與成功後的畫面更新。完成基本流程後,再逐步加入更細緻的體驗優化。

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