国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

WordPress中利用AJAX技術(shù)進(jìn)行評論提交的實現(xiàn)示例

2019-11-20 10:49:02
字體:
供稿:網(wǎng)友

一直對 WordPress 的 Ajax 交互研究感興趣,也一直很關(guān)注于這方面的技術(shù),談到 WordPress Ajax 就不得不談到評論 Ajax提交,作為一個博客、論壇評論的 Ajax 提交不僅可以改善用戶體驗,還可以大幅縮減服務(wù)器開支,畢竟輸出單條評論內(nèi)容比重新組織輸出一個頁面要簡單的多。 雖說現(xiàn)在訪問量一直比較低,不存在服務(wù)器壓力的問題,但一向注重用戶體驗的我,當(dāng)然不能放棄這么一個提升用戶體驗的機(jī)會。今天抽了一下午的空,把這個主題的 Ajax 評論提交初步完成了。

直接開門見山,直接上代碼:(原理及思路在最后)
根據(jù)自己主題不同結(jié)構(gòu),以下代碼請自行調(diào)整。

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

//以下大部分代碼出自 yinheli 經(jīng)由該部分代碼,排除部分錯誤、優(yōu)化精簡得出以下代碼。//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);//掛一個評論太快,返回內(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 源代碼 。詳見: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('是不是應(yīng)該寫點什么再提交?');// 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('評論重復(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)用評論函數(shù),換成你的函數(shù)名。 die();}}add_action('init', 'ajax_comment');

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

if (jQuery('#commentform').length) {  jQuery('#commentform').submit(function(){  // 截獲提交動作//ID為 commentform 的表單提交時發(fā)生的函數(shù),也就是整個留言輸入框 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ā)生錯誤時        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)需求,因為沒有時間,所以就沒有再進(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é)果并顯示
思路:
點擊提交按鈕后,Javascript 截獲提交動作
截獲提交的各項數(shù)據(jù)(Name、Email、Web、Comment-text)
利用 Javascript Jquery 模擬瀏覽器提交POST(Name、Email、Web、Comment-text)請求之WordPress
Function.php 文件中構(gòu)造一個接受請求的函數(shù),即本列中ajax_comment函數(shù)
如果請求無錯誤,輸出正確結(jié)果
如果請求有錯誤,輸出錯誤結(jié)果
Javascript 獲得正確結(jié)果,動態(tài)添加到評論列表中
Javascript 獲得錯誤結(jié)果,動態(tài)添加到提交提示欄
改進(jìn)
樣式方面,我確實沒什么美感,所以正在學(xué)習(xí)中。
提交按鈕在點擊至獲得返回結(jié)果后3秒的時間里應(yīng)該都是變灰失效狀態(tài),這一點之前因為在本機(jī)測試,提交瞬間完成沒有注意到,遠(yuǎn)程測試的時候發(fā)現(xiàn)了,但要改的話還要進(jìn)行測試,時間太緊就不改了,有機(jī)會再改進(jìn)一下。

總結(jié)
因為 WordPress 主題中評論樣式的自由性、多樣性,所以貌似至今一直沒有一款通用性的AJAX 評論插件,
一些高手也只能在優(yōu)化自己博客之余,把思路和部分通用核心代碼做一下公布,
所以想要實現(xiàn)一些炫酷的功能要不有高人幫你,
要不你就只能好好學(xué)代碼,期待有一日能夠厚積薄發(fā)了。
效果請自行提交評論驗證。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 洪洞县| 正蓝旗| 白银市| 盱眙县| 华安县| 雷波县| 沙洋县| 湛江市| 常熟市| 滕州市| 玛多县| 台中市| 乌拉特前旗| 同心县| 龙门县| 泉州市| 鄂托克前旗| 大城县| 天水市| 敦煌市| 达尔| 嘉善县| 荔浦县| 涞水县| 长汀县| 保定市| 桐庐县| 渝北区| 贵州省| 江川县| 台东县| 南和县| 灵台县| 德保县| 华亭县| 开封县| 靖西县| 宣威市| 绥江县| 绥江县| 合水县|