启用提交评论而不重新加载页面(使用AJAX)?

时间:2012-06-04 作者:its_me

当用户写评论并点击提交按钮时,WordPress会在评论显示给用户之前重新加载页面。

是否有基于Ajax的解决方案允许用户动态提交问题,而无需刷新整个页面?

2 个回复
最合适的回答,由SO网友:its_me 整理而成

保存以下javascrip文件wpse54189-ajax-comments.js 在插件文件夹中-例如plugins/plug-in-name/js (或者,如果必须转到主题,请在主题文件夹中)。

/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 */

(function(a){a.fn.autoResize=function(j){var b=a.extend({onResize:function(){},animate:true,animateDuration:150,animateCallback:function(){},extraSpace:20,limit:1000},j);this.filter(\'textarea\').each(function(){var c=a(this).css({resize:\'none\',\'overflow-y\':\'hidden\'}),k=c.height(),f=(function(){var l=[\'height\',\'width\',\'lineHeight\',\'textDecoration\',\'letterSpacing\'],h={};a.each(l,function(d,e){h[e]=c.css(e)});return c.clone().removeAttr(\'id\').removeAttr(\'name\').css({position:\'absolute\',top:0,left:-9999}).css(h).attr(\'tabIndex\',\'-1\').insertBefore(c)})(),i=null,g=function(){f.height(0).val(a(this).val()).scrollTop(10000);var d=Math.max(f.scrollTop(),k)+b.extraSpace,e=a(this).add(f);if(i===d){return}i=d;if(d>=b.limit){a(this).css(\'overflow-y\',\'\');return}b.onResize.call(this);b.animate&&c.css(\'display\')===\'block\'?e.stop().animate({height:d},b.animateDuration,b.animateCallback):e.height(d)};c.unbind(\'.dynSiz\').bind(\'keyup.dynSiz\',g).bind(\'keydown.dynSiz\',g).bind(\'change.dynSiz\',g)});return this}})(jQuery);


/*
 * Source: wp-comment-master WordPress Plugin
 * URL: http://wordpress.org/extend/plugins/wp-comment-master/
 * Author URI: http://yjlblog.com
 * Version: 1.7
 * Last Updated: 2011-6-6
 */

   var $commentlist=jQuery(\'.commentlist\');
   var $respond=jQuery(\'#respond\');
   var $message=jQuery(\'<span class="yjl-mes"></span>\').appendTo("#commentform");;
   var $list=$commentlist.children();
   var totalCom=$list.length;
   var $textarea=$respond.find(\'#comment\').attr(\'rows\',\'8\');

   var currentPage=0,$number,numPerPage,totalPage,$reply;

   //track a reply comment
   jQuery(\'.comment-reply-link\').live(\'click\',function(){
       $reply=true;
   });
   var $cancel=jQuery(\'#cancel-comment-reply-link\').click(function(){
       $reply=false;
   });

   /*
    *if Ajax comment posting is enabled
    */
   jQuery(\'#commentform\').submit(function(){
       jQuery.ajax({
         beforeSend:function(xhr){
            xhr.setRequestHeader("If-Modified-Since","0");
            $message.empty().append(\'<img src="\'+yjlSettings.gifUrl+\'" alt="processing...">\');
         },
         type:\'post\',
         url:jQuery(this).attr(\'action\'),
         data:jQuery(this).serialize(),
         dataType:\'html\',
         error:function(xhr){
             if(xhr.status==500){
               $message.empty().append(xhr.responseText.split(\'<p>\')[1].split(\'</p>\')[0]);
             }
             else if(xhr.status==\'timeout\'){
               $message.empty().append((yjlSettings.timeOut!=\'\'?yjlSettings.timeOut:\'Error:Server time out,try again!\'));
             }
             else{
               $message.empty().append((yjlSettings.fast!=\'\'?yjlSettings.fast:\'Please slow down,you are posting to fast!\'));
             }
         },
         success:function(data){
            $message.empty().append((yjlSettings.thank!=\'\'?yjlSettings.thank:\'Thank you for your comment!\'));
            $newComList=jQuery(data).find(\'.commentlist\');
            if(totalCom>0){
               if($reply)$cancel.trigger(\'click\');
               else {
                   if(yjlSettings.order==\'desc\')currentPage=0;
                   else { getTotal($newComList);currentPage=totalPage-1;}
               }
               if(yjlSettings.pagination==\'disable\' || yjlSettings.pagerPos==\'after\')
                        $commentlist.prev().replaceWith($newComList.prev());
               else $commentlist.prev().prev().replaceWith($newComList.prev());                     
               $commentlist.replaceWith($newComList);                            
            }else{
               if(yjlSettings.repForm==\'disable\')$newComList.prev().andSelf().insertBefore($respond);
               else $newComList.prev().andSelf().insertAfter($respond);
            }
            $commentlist=$newComList;
            if(yjlSettings.pagination!=\'disable\')pagination();
            $textarea.val(\'\'); 
         }
       });//end of ajax
      return false;
   });//end of submit function

   if(yjlSettings.autoGrow!=\'disable\'){
      $textarea.autoResize({
       // On resize:
       onResize : function() {
        jQuery(this).css({opacity:0.8});
      },
      // After resize:
      animateCallback : function() {
        jQuery(this).css({opacity:1});
      },
      // Quite slow animation:
      animateDuration : 300,
      // More extra space:
      extraSpace : 20
      });
   }
上面的代码使用一个变量来存储“ajax”加载图像的位置(见下文)。我们需要给这个变量图像的位置,它应该是您的插件文件夹,比如plugins/plug-in-name/img, (或者,如果必须,也可以是主题文件夹)。我们将使用wp_localise_script.

但首先,我们需要在WordPress中注册此脚本,将jquery列为依赖项:

add_action(\'init\',\'wpse54189_register_script\');
function wpse54189_register_script(){
    //Register script
    wp_register_script( \'wpse54189_ajax_comment\', plugin_dir_path(__FILE__ ).\'js/wpse54189-ajax-comments.js\',array(\'jquery\'));

    //Add global variable storing ajax image
    wp_localize_script( \'wpse54189_ajax_comment\', \'yjlSettings\', array(
         \'gifUrl\'=> plugin_dir_path(__FILE__ ).\'img/ajax-loader.gif\',

         /* remove this line if you don\'t want the comment textbox\'s height
         to increase with the size of comment. */
         \'autoGrow\'=> \'enable\'
    ));

}
然后,当您希望将文件排队时:wp_enqueue_script(\'wpse54189_ajax_comment\') - 这将自动打印变量,并确保jquery提前加载。

这可以放在模板文件中,或者对于插件,您可以将脚本排队到挂钩上(例如comment_form_before 挂钩):

add_action(\'comment_form_before\',\'wpse54189_register_script\'){
     wp_enqueue_script(\'wpse54189_ajax_comment\')
}
您可以从here. 或者简单地使用:

Loading gif

所有JavaScript代码都是从wp-comment-master 插件(当然,我删除了不必要的代码片段,只保留了所需的内容)。

SO网友:Eugene Manuilov

是的,有很多解决方案,请在此处查看:http://wordpress.org/extend/plugins/search.php?q=ajax+comments

结束

相关推荐

如何将WordPress的CSS样式应用到jQueryUi对话框中?

我正在开发一个wordpress插件,并成功地使用jQuery显示了一个模式对话框。问题是,我还将列表和按钮显示到该对话框中,我希望这些按钮和列表看起来像wordpress中的按钮和列表。换句话说,我希望我的对话框“继承”WP样式,以便按钮和列表看起来很好。我会非常感谢你的帮助,因为(如果你想叫我傻瓜的话)我已经花了三天时间在这上面了。谢谢