原文出自绛木子博客:https://lixianhua.com/te_ajax_comment_without_pluign.html
为了不运用插件完成Ajax批评功用须要完成:
1,监听批评表单,改用ajax体式格局提交
2,建立新的批评表单提交地点(用Typecho主题供应的体系要领themeInit完成)
当接见文章加载主题时,themeInit要领起首被加载,可在此要领中推断是不是为增加批评的操纵,即新的批评表单地点为文章的链接(permalink).详细推断要领以下
// 主题初始化function themeInit($archive){ // 推断是不是是增加批评的操纵 // 为文章或页面、post操纵,且包括参数`themeAction=comment`(自定义) if($archive->is('single') && $archive->request->isPost() && $archive->request->is('themeAction=comment')){ // 为增加批评的操纵时 ajaxComment($archive); }}要完成ajax批评,则没法运用体系默许的feedback,这里我们将复制feedback功用并革新为我们须要的要领
/** * ajaxComment * 完成Ajax批评的要领(完成feedback中的comment功用) * @param Widget_Archive $archive * @return void */function ajaxComment($archive){ $options = Helper::options(); $user = Typecho_Widget::widget('Widget_User'); $db = Typecho_Db::get(); // Security 考证不经由过程时会直接跳转,所以须要本身举行推断 // 须要开启反垃圾庇护,此时将不考证泉源 if($archive->request->get('_') != Helper::security()->getToken($archive->request->getReferer())){ $archive->response->throwJson(array('status'=>0,'msg'=>_t('不法要求'))); } /** 批评封闭 */ if(!$archive->allow('comment')){ $archive->response->throwJson(array('status'=>0,'msg'=>_t('批评已封闭'))); } /** 搜检ip批评距离 */ if (!$user->pass('editor', true) && $archive->authorId != $user->uid && $options->commentsPostIntervalEnable){ $latestComment = $db->fetchRow($db->select('created')->from('table.comments') ->where('cid = ?', $archive->cid) ->where('ip = ?', $archive->request->getIp()) ->order('created', Typecho_Db::SORT_DESC) ->limit(1)); if ($latestComment && ($options->gmtTime - $latestComment['created'] > 0 && $options->gmtTime - $latestComment['created'] < $options->commentsPostInterval)) { $archive->response->throwJson(array('status'=>0,'msg'=>_t('对不起, 您的谈话过于频仍, 请稍侯再次宣布'))); } } $comment = array( 'cid' => $archive->cid, 'created' => $options->gmtTime, 'agent' => $archive->request->getAgent(), 'ip' => $archive->request->getIp(), 'ownerId' => $archive->author->uid, 'type' => 'comment', 'status' => !$archive->allow('edit') && $options->commentsRequireModeration ? 'waiting' : 'approved' ); /** 推断父节点 */ if ($parentId = $archive->request->filter('int')->get('parent')) { if ($options->commentsThreaded && ($parent = $db->fetchRow($db->select('coid', 'cid')->from('table.comments') ->where('coid = ?', $parentId))) && $archive->cid == $parent['cid']) { $comment['parent'] = $parentId; } else { $archive->response->throwJson(array('status'=>0,'msg'=>_t('父级批评不存在'))); } } $feedback = Typecho_Widget::widget('Widget_Feedback'); //磨练花样 $validator = new Typecho_Validate(); $validator->addRule('author', 'required', _t('必需填写用户名')); $validator->addRule('author', 'xssCheck', _t('请不要在用户名中运用特别字符')); $validator->addRule('author', array($feedback, 'requireUserLogin'), _t('您所运用的用户名已被注册,请登录后再次提交')); $validator->addRule('author', 'maxLength', _t('用户名最多包括200个字符'), 200); if ($options->commentsRequireMail && !$user->hasLogin()) { $validator->addRule('mail', 'required', _t('必需填写电子邮箱地点')); } $validator->addRule('mail', 'email', _t('邮箱地点不合法')); $validator->addRule('mail', 'maxLength', _t('电子邮箱最多包括200个字符'), 200); if ($options->commentsRequireUrl && !$user->hasLogin()) { $validator->addRule('url', 'required', _t('必需填写个人主页')); } $validator->addRule('url', 'url', _t('个人主页地点花样毛病')); $validator->addRule('url', 'maxLength', _t('个人主页地点最多包括200个字符'), 200); $validator->addRule('text', 'required', _t('必需填写批评内容')); $comment['text'] = $archive->request->text; /** 对平常匿名接见者,将用户数据保留一个月 */ if (!$user->hasLogin()) { /** Anti-XSS */ $comment['author'] = $archive->request->filter('trim')->author; $comment['mail'] = $archive->request->filter('trim')->mail; $comment['url'] = $archive->request->filter('trim')->url; /** 修正用户提交的url */ if (!empty($comment['url'])) { $urlParams = parse_url($comment['url']); if (!isset($urlParams['scheme'])) { $comment['url'] = 'http://' . $comment['url']; } } $expire = $options->gmtTime + $options->timezone + 30*24*3600; Typecho_Cookie::set('__typecho_remember_author', $comment['author'], $expire); Typecho_Cookie::set('__typecho_remember_mail', $comment['mail'], $expire); Typecho_Cookie::set('__typecho_remember_url', $comment['url'], $expire); } else { $comment['author'] = $user->screenName; $comment['mail'] = $user->mail; $comment['url'] = $user->url; /** 纪录登录用户的id */ $comment['authorId'] = $user->uid; } /** 批评者之前须有批评经由过程了考核 */ if (!$options->commentsRequireModeration && $options->commentsWhitelist) { if ($feedback->size($feedback->select()->where('author = ? AND mail = ? AND status = ?', $comment['author'], $comment['mail'], 'approved'))) { $comment['status'] = 'approved'; } else { $comment['status'] = 'waiting'; } } if ($error = $validator->run($comment)) { $archive->response->throwJson(array('status'=>0,'msg'=> implode(';',$error))); } /** 增加批评 */ $commentId = $feedback->insert($comment); if(!$commentId){ $archive->response->throwJson(array('status'=>0,'msg'=>_t('批评失利'))); } Typecho_Cookie::delete('__typecho_remember_text'); $db->fetchRow($feedback->select()->where('coid = ?', $commentId) ->limit(1), array($feedback, 'push')); // 返回批评数据 $data = array( 'cid' => $feedback->cid, 'coid' => $feedback->coid, 'parent' => $feedback->parent, 'mail' => $feedback->mail, 'url' => $feedback->url, 'ip' => $feedback->ip, 'agent' => $feedback->agent, 'author' => $feedback->author, 'authorId' => $feedback->authorId, 'permalink' => $feedback->permalink, 'created' => $feedback->created, 'datetime' => $feedback->date->format('Y-m-d H:i:s'), 'status' => $feedback->status, ); // 批评内容 ob_start(); $feedback->content(); $data['content'] = ob_get_clean(); $data['avatar'] = Typecho_Common::gravatarUrl($data['mail'], 48, Helper::options()->commentsAvatarRating, NULL, $archive->request->isSecure()); $archive->response->throwJson(array('status'=>1,'comment'=>$data));}当已在functions.php文件中增加完上述要领时,就已能够吸收ajax批评了。
此时我们须要修正批评表单增加的体式格局及提交的地点。
在footer.php文件中增加要领
// 依靠jquery,请自行加载$(function(){ // 监听批评表单提交 $('#comment-form').submit(function(){ var form = $(this), params = form.serialize(); // 增加functions.php中定义的推断参数 params += '&themeAction=comment'; // 剖析新批评并附加到批评列表 var appendComment = function(comment){ // 批评列表 var el = $('#comments > .comment-list'); if(0 != comment.parent){ // 子批评则从新定位批评列表 var el = $('#comment-'+comment.parent); // 父批评不存在子批评时 if(el.find('.comment-children').length < 1){ $('<div class="comment-children"><ol class="comment-list"></ol></div>').appendTo(el); }else if(el.find('.comment-children > .comment-list').length <1){ $('<ol class="comment-list"></ol>').appendTo(el.find('.comment-children')); } el = $('#comment-'+comment.parent).find('.comment-children').find('.comment-list'); } if(0 == el.length){ $('<ol class="comment-list"></ol>').appendTo($('#comments')); el = $('#comments > .comment-list'); } // 批评html模板,依据详细主题定制 var html = '<li id="comment-{coid}" class="comment-body comment-ajax"><div class="comment-author"><span><img class="avatar" src="{avatar}" alt="{author}" width="32" height="32"></span><cite class="fn">{author}</cite></div><div class="comment-meta"><a href="{permalink}"><time>{datetime}</time></a></div><div class="comment-content">{content}</div></li>'; $.each(comment,function(k,v){ regExp = new RegExp('{'+k+'}', 'g'); html = html.replace(regExp, v); }); $(html).appendTo(el); } // ajax提交批评 $.ajax({ url: '<?php $this->permalink();?>', type: 'POST', data: params, dataType: 'json', beforeSend: function() { form.find('.submit').addClass('loading').html('<i class="icon icon-loading icon-pulse"></i> 提交中...').attr('disabled','disabled');}, complete: function() { form.find('.submit').removeClass('loading').html('提交批评').removeAttr('disabled');}, success: function(result){ if(1 == result.status){ // 新批评附加到批评列表 appendComment(result.comment); form.find('textarea').val(''); }else{ // 提示毛病音讯 alert(undefined === result.msg ? '<?php _e('批评失足!');?>' : result.msg); } }, error:function(xhr, ajaxOptions, thrownError){ alert('批评失利,请重试'); } }); return false; });});ajax批评须要自定义批评模板,猎取运用其他体式格局拼接批评html。
批评form表单的提交按钮须要增加class="submit"或修正代码为其他自定义的class
注:需开启批评的反垃圾庇护
一,经由过程ajax举行批评,邮件关照插件并不会发出关照!
缘由是由于重写了批评的函数,而函数中没写批评完成后触发插件接口,所以邮件关照插件不会发邮件给作者。
处理要领也很简单在上述php代码$db->fetchRow($feedback->select()->where('coid = ?', $commentId)->limit(1), array($feedback, 'push'));背面到场$feedback->pluginHandle()->finishComment($feedback);即可。
二,批评过滤插件也会失效!
缘由也是没有写入批评过滤的接口
这个接口我试着往里面写,没有胜利,所以换了个体式格局来处理,直接在里面写过滤,而不是用插件过滤批评。
比如在$commentId = $feedback->insert($comment);前面到场
if (preg_match("/[\x{4e00}-\x{9fa5}]/u", $comment['text']) == 0) {$archive->response->throwJson(array('status'=>0,'msg'=>_t('批评内容请不少于一个中文汉字')));}即可屏障非中文批评,发起同时运用批评过滤插件,由于有些垃圾批评是经由过程批评机器人完成的,并不会经由ajax批评,所以还须要继续运用批评过滤插件,亦或许在模板层面上用上批评过滤接口(我是这么做的,现在来看大概是有结果的)

评论列表