一直對(duì) WordPress 的 Ajax 交互研究感興趣,也一直很關(guān)注于這方面的技術(shù),談到 WordPress Ajax 就不得不談到評(píng)論 Ajax提交,作為一個(gè)博客、論壇評(píng)論的 Ajax 提交不僅可以改善用戶體驗(yàn),還可以大幅縮減服務(wù)器開(kāi)支,畢竟輸出單條評(píng)論內(nèi)容比重新組織輸出一個(gè)頁(yè)面要簡(jiǎn)單的多。 雖說(shuō)現(xiàn)在訪問(wèn)量一直比較低,不存在服務(wù)器壓力的問(wèn)題,但一向注重用戶體驗(yàn)的我,當(dāng)然不能放棄這么一個(gè)提升用戶體驗(yàn)的機(jī)會(huì)。今天抽了一下午的空,把這個(gè)主題的 Ajax 評(píng)論提交初步完成了。
直接開(kāi)門(mén)見(jiàn)山,直接上代碼:(原理及思路在最后)
根據(jù)自己主題不同結(jié)構(gòu),以下代碼請(qǐng)自行調(diào)整。
WordPress Ajax 提交評(píng)論 PHP 代碼
在主題 function.php 文件中加入如下部分。
//以下大部分代碼出自 yinheli 經(jīng)由該部分代碼,排除部分錯(cuò)誤、優(yōu)化精簡(jiǎn)得出以下代碼。//yinheli博客不做了,所以這里就不給鏈接了。//Edited by XiangZi DEC.17TH 2011function fail($s) {//虛擬錯(cuò)誤頭部分 header('HTTP/1.0 500 Internal Server Error'); echo $s; exit;}function ajax_post_comment_slow (){ fail('用不用說(shuō)這么快?想好了再說(shuō)!');}//評(píng)論太快輸出代碼。add_filter('comment_flood_trigger','ajax_post_comment_slow', 0);//掛一個(gè)評(píng)論太快,返回內(nèi)容的鉤子function ajax_comment(){// Ajax php 響應(yīng)部分代碼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 源代碼 。詳見(jiàn):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('火星人?注冊(cè)個(gè)?');}$comment_type = '';if ( get_option('require_name_email') && !$user->ID ) { if ( 6> strlen($comment_author_email) || '' == $comment_author ) fail('Oopps,名字[Name]或郵箱[email]不對(duì)。'); elseif ( !is_email($comment_author_email)) fail('Oopps,郵箱地址[Email]不對(duì)。');}if ( '' == $comment_content ) fail('是不是應(yīng)該寫(xiě)點(diǎn)什么再提交?');// 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('評(píng)論重復(fù)了!有木有!');}$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);//這是我的調(diào)用評(píng)論函數(shù),換成你的函數(shù)名。 die();}}add_action('init', 'ajax_comment');
Javascript 中代碼
注意:以下代碼需要 Jquery 框架支援。
javascript onload 代碼中加入以下部分。
if (jQuery('#commentform').length) { jQuery('#commentform').submit(function(){ // 截獲提交動(dòng)作//ID為 commentform 的表單提交時(shí)發(fā)生的函數(shù),也就是整個(gè)留言輸入框 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) { //發(fā)生錯(cuò)誤時(shí) 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; } );}
注:代碼仍有改進(jìn)需求,因?yàn)闆](méi)有時(shí)間,所以就沒(méi)有再進(jìn)化。
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 提交數(shù)據(jù)
php響應(yīng)并輸出結(jié)果
Javascript 得到結(jié)果并顯示
思路:
點(diǎn)擊提交按鈕后,Javascript 截獲提交動(dòng)作
截獲提交的各項(xiàng)數(shù)據(jù)(Name、Email、Web、Comment-text)
利用 Javascript Jquery 模擬瀏覽器提交POST(Name、Email、Web、Comment-text)請(qǐng)求之WordPress
Function.php 文件中構(gòu)造一個(gè)接受請(qǐng)求的函數(shù),即本列中ajax_comment函數(shù)
如果請(qǐng)求無(wú)錯(cuò)誤,輸出正確結(jié)果
如果請(qǐng)求有錯(cuò)誤,輸出錯(cuò)誤結(jié)果
Javascript 獲得正確結(jié)果,動(dòng)態(tài)添加到評(píng)論列表中
Javascript 獲得錯(cuò)誤結(jié)果,動(dòng)態(tài)添加到提交提示欄
改進(jìn)
樣式方面,我確實(shí)沒(méi)什么美感,所以正在學(xué)習(xí)中。
提交按鈕在點(diǎn)擊至獲得返回結(jié)果后3秒的時(shí)間里應(yīng)該都是變灰失效狀態(tài),這一點(diǎn)之前因?yàn)樵诒緳C(jī)測(cè)試,提交瞬間完成沒(méi)有注意到,遠(yuǎn)程測(cè)試的時(shí)候發(fā)現(xiàn)了,但要改的話還要進(jìn)行測(cè)試,時(shí)間太緊就不改了,有機(jī)會(huì)再改進(jìn)一下。
總結(jié)
因?yàn)?WordPress 主題中評(píng)論樣式的自由性、多樣性,所以貌似至今一直沒(méi)有一款通用性的AJAX 評(píng)論插件,
一些高手也只能在優(yōu)化自己博客之余,把思路和部分通用核心代碼做一下公布,
所以想要實(shí)現(xiàn)一些炫酷的功能要不有高人幫你,
要不你就只能好好學(xué)代碼,期待有一日能夠厚積薄發(fā)了。
效果請(qǐng)自行提交評(píng)論驗(yàn)證。