WordPress中利用AJAX技術進行評論提交的實現樣本_javascript技巧

來源:互聯網
上載者:User

一直對 WordPress 的 Ajax 互動研究感興趣,也一直很關注於這方面的技術,談到 WordPress Ajax 就不得不談到評論 Ajax提交,作為一個部落格、論壇評論的 Ajax 提交不僅可以改善使用者體驗,還可以大幅縮減伺服器開支,畢竟輸出單條評論內容比重新組織輸出一個頁面要簡單的多。 雖說現在訪問量一直比較低,不存在伺服器壓力的問題,但一向注重使用者體驗的我,當然不能放棄這麼一個提升使用者體驗的機會。今天抽了一下午的空,把這個主題的 Ajax 評論提交初步完成了。

直接開門見山,直接上代碼:(原理及思路在最後)
根據自己主題不同結構,以下代碼請自行調整。

WordPress Ajax 提交評論 PHP 代碼
在主題 function.php 檔案中加入如下部分。

//以下大部分代碼出自 yinheli 經由該部分代碼,排除部分錯誤、最佳化精簡得出以下代碼。//yinheli部落格不做了,所以這裡就不給連結了。//Edited by XiangZi DEC.17TH 2011function fail($s) {//虛擬錯誤頭部分  header('HTTP/1.0 500 Internal Server Error');  echo $s;  exit;}function ajax_post_comment_slow (){ fail('用不用說這麼快?想好了再說!');}//評論太快輸出代碼。add_filter('comment_flood_trigger','ajax_post_comment_slow', 0);//掛一個評論太快,返回內容的鉤子function ajax_comment(){// Ajax php 響應部分代碼if($_POST['action'] == 'ajax_comment') {  global $wpdb, $db_check;    // Check DB    if(!$wpdb->dbh) {      echo('Our database has issues. Try again later.');  die();    } nocache_headers();$comment_post_ID = (int) $_POST['comment_post_ID']; $status = $wpdb->get_row("SELECT post_status, comment_status FROM $wpdb->posts WHERE ID = '$comment_post_ID'");if ( empty($status->comment_status) ) {//這一套判斷貌似抄的 wp 原始碼 。詳見:include/comment.php  do_action('comment_id_not_found', $comment_post_ID);  fail('The post you are trying to comment on does not currently exist in the database.');} elseif ( 'closed' == $status->comment_status ) {  do_action('comment_closed', $comment_post_ID);;  fail('Sorry, comments are closed for this item.');} elseif ( in_array($status->post_status, array('draft', 'pending') ) ) {  do_action('comment_on_draft', $comment_post_ID);  fail('The post you are trying to comment on has not been published.');}$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 the user is logged in$user = wp_get_current_user();if ( $user->ID ) {  $comment_author    = $wpdb->escape($user->display_name);  $comment_author_email = $wpdb->escape($user->user_email);  $comment_author_url  = $wpdb->escape($user->user_url);  if ( current_user_can('unfiltered_html') ) {    if ( wp_create_nonce('unfiltered-html-comment_' . $comment_post_ID) != $_POST['_wp_unfiltered_html_comment'] ) {      kses_remove_filters(); // start with a clean slate      kses_init_filters(); // set up the filters    }  }} else {  if ( get_option('comment_registration') )    fail('火星人?註冊個?');}$comment_type = '';if ( get_option('require_name_email') && !$user->ID ) {  if ( 6> strlen($comment_author_email) || '' == $comment_author )    fail('Oopps,名字[Name]或郵箱[email]不對。');  elseif ( !is_email($comment_author_email))    fail('Oopps,郵箱地址[Email]不對。');}if ( '' == $comment_content )  fail('是不是應該寫點什麼再提交?');// Simple duplicate check$dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' ";$dupe .= ") AND comment_content = '$comment_content' LIMIT 1";if ( $wpdb->get_var($dupe) ) {  fail('評論重複了!有木有!');}$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID');if( !$user->ID ){ $result_set = $wpdb->get_results("SELECT display_name, user_email FROM $wpdb->users WHERE display_name = '" . $comment_author . "' OR user_email = '" . $comment_author_email . "'"); if ($result_set) { if ($result_set[0]->display_name == $comment_author){ fail('博主你也敢冒充?'); } else { fail('博主你也敢冒充?'); } }}$comment_id = wp_new_comment( $commentdata );$comment = get_comment($comment_id); if( !$user->ID ){ setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + 30000000, COOKIEPATH, COOKIE_DOMAIN); setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + 30000000, COOKIEPATH, COOKIE_DOMAIN); setcookie('comment_author_url_' . COOKIEHASH, clean_url($comment->comment_author_url), time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);}@header('Content-type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset')); xz_comment($comment, null);//這是我的調用評論函數,換成你的函數名。 die();}}add_action('init', 'ajax_comment');

Javascript 中代碼
注意:以下代碼需要 Jquery 架構支援。
javascript onload 代碼中加入以下部分。

if (jQuery('#commentform').length) {  jQuery('#commentform').submit(function(){  // 截獲提交動作//ID為 commentform 的表單提交時發生的函數,也就是整個留言輸入框 form 的ID。 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();  //隱藏 submit        jQuery('#commenterror').fadeIn(); //顯示 error       },      success: function(data) {        jQuery('textarea').each(function(){          this.value='';        });        jQuery('#commenterror').fadeOut();        if(jQuery(".commentlist li.comment").first().length != 0){jQuery(".commentlist li.comment").first().before(data)}          else {jQuery("ol.commentlist").append(data)}        jQuery(".commentlist li.comment").first().hide(0,function(){$(this).slideDown(1000)});        jQuery('#cmt-submit').attr('disabled', true).css({"background-color":"#6C6C6C","color":"#E0E0E0"});        jQuery('#commentload').fadeOut(1600); setTimeout(function() {        jQuery('#cmt-submit').removeAttr('disabled').css({"background-color":"#0086C5","color":"#FFFFFF"});        },3000);       }    });    return false;  } );}

註:代碼仍有改進需求,因為沒有時間,所以就沒有再進化。

CSS 代碼
css 隨意部分添加。

#commentload,#commenterror{ display: none; margin: 5px 0 0 0; color:#D29A04; float: left; font-size:16px; padding:0 0 0 20px;}#commentload{ background: url("img/loading.gif") no-repeat bottom left ;}#commenterror{ background: url("img/error.png") no-repeat bottom left ;}

原理、思路
原理:
Javascript 提交資料
php響應並輸出結果
Javascript 得到結果並顯示
思路:
點擊提交按鈕後,Javascript 截獲提交動作
截獲提交的各項資料(Name、Email、Web、Comment-text)
利用 Javascript Jquery 類比瀏覽器提交POST(Name、Email、Web、Comment-text)請求之WordPress
Function.php 檔案中構造一個接受請求的函數,即本列中ajax_comment函數
如果請求無錯誤,輸出正確結果
如果請求有錯誤,輸出錯誤結果
Javascript 獲得正確結果,動態添加到評論列表中
Javascript 獲得錯誤結果,動態添加到提交提示欄
改進
樣式方面,我確實沒什麼美感,所以正在學習中。
提交按鈕在點擊至獲得返回結果後3秒的時間裡應該都是變灰失效狀態,這一點之前因為在本機測試,提交瞬間完成沒有注意到,遠程測試的時候發現了,但要改的話還要進行測試,時間太緊就不改了,有機會再改進一下。

總結
因為 WordPress 主題中評論樣式的自由性、多樣性,所以貌似至今一直沒有一款通用性的AJAX 評論外掛程式,
一些高手也只能在最佳化自己部落格之餘,把思路和部分通用核心代碼做一下公布,
所以想要實現一些炫酷的功能要不有高人幫你,
要不你就只能好好學代碼,期待有一日能夠厚積薄發了。
效果請自行提交評論驗證。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.