AJAX Commentsプラグインを使用して、コメント POST を Ajax 化していたのだが、最新バージョンの 2.09 では有料になったようだ。
そんなわけで jQuery で、同等のことができるようなコードを書いてみた。
基にしたコードは、以前 AJAX Comments プラグインを jQuery 対応させたときに書いたもの。
AJAX Comments プラグインでは、コメント POST 先を独自の PHP にしているが、今回のコードは WordPress の標準のまま wp-comments-post.php に対して POST している。
$(function(){
var commentform_id = 'commentform'; // コメントフォームの ID
var commentlist_id = 'commentlist'; // コメントリストの ID
var loading_img = 'loading.gif'; // コメント POST 時に表示する画像
var loading_txt = 'Submitting Comment...'; // コメント POST 時に表示する文字
// コメントフォーム
var commentform = $('#' + commentform_id);
// コメント POST 開始時の処理 (form を使用できないように block)
commentform.ajaxStart(function(){
this.submit.disabled = true; // disable submit
$(this).block('<div style="margin:0 auto;padding:0 0 0 23px;width:100px;font:normal 12px Arial;background:url(' + loading_img + ') no-repeat 0 50%;">' + loading_txt + '</div>',{ border: '1px solid #8C8C8C' });
});
// コメント POST エラー時の処理
commentform.ajaxError(function(request, settings){
// alert message
alert(settings.responseText.replace(/[\r\n]/g, '').replace(/.*<p>(.*?)<\/p>.*/i, '$1'));
});
// コメント POST 終了時の処理
commentform.ajaxStop(function(){
this.submit.disabled = false; // enable submit
$(this).unblock();
});
// コメント POST 処理
commentform.submit(function(){
// IE Hack
if ($.browser.msie) {
var redirect_to = $('input[@name=redirect_to]', $(this));
var date = new Date();
redirect_to.attr('value', redirect_to.attr('value') + '?comments=' + date.getYear() + date.getMonth() + date.getDate());
}
// POST
var url = $(this).attr('action');
var param = $('input, textarea', $(this)).serialize();
$.post(
url,
param,
function(responseText, status) {
// コメントリストの取得
var commentlist = $('#' + commentlist_id);
if (commentlist.length <= 0) {
commentlist = $('.' + commentlist_id + ':first');
if(commentlist.length <= 0) {
commentlist = $('<ul id="' + commentlist_id + '"></ul>');
commentform.prepend(ul);
}
}
// コメントリストに response をセットする
var re = new RegExp('<[ou]l .*(class|id)=["\']' + commentlist_id + '["\'].*?>(<li.*?>.*?<\/li>)<\/[ou]l>', 'i');
var comments = responseText.replace(/[\r\n]/g, '').match(re);
if (comments) {
// コメントリストへの追加
if (comments.length > 1) {
commentlist.animate({opacity:'hide'}, 'normal', function(){
$(this).html(comments[2]).animate({opacity:'show'}, 'fast');
});
}
$('textarea', commentform).val(''); // Reset comment
} else {
// エラーメッセージ表示
alert(responseText.replace(/[\r\n]/g, '').replace(/.*<p>(.*?)<\/p>.*/i, '$1'));
}
}
);
return false;
});
});
jQuery BlockUI Plugin を使用して、コメント POST 時にコメントフォームをいじれないようにしている。
つぶやく
トラックバック & ピンバック » 表示する
コメント