博客学堂
首页>>我的博客>>wordpress>> 使用 jQuery 实现Ajax留言

使用 jQuery 实现Ajax留言

来源:北极冰仔部落格  | 添加时间:2008-1-6 13:22:50 |   | 我要投稿 | 提问

今天花了点时间在自己的 blog 上实现了非插件式的 Ajax 留言功能,当然,还是基于我们很好很强大的 jQuery 框架。基本思路就是利用 jQuery 的 Ajax API 把留言数据提交给 comments-ajax.php 完成留言,我们分三步实现,第一步要先改造 comments.php,第二步实现 jQuery 代码,第三步编写一个 comments-ajax.php 用来接收留言数据并完成对 WP 数据库的操作。

改造 comments.php

这一步不是必须的,你完全可以写一份适用于非标准的 comments.php 的 jQuery 代码,不过还是建议你把留言模板中的各个元素的 ID 定义标准,譬如把填写留言信息的表单(form)的 ID 设为 #commentform,留言 列表 ul 或 ol 的 ID 设为 #commentlist 等等。另外,视具体情况,你可能需要在合适的地方新增两个 span 元素,ID 分别设为 #commentload 和 #commenterror,用来显示留言提交状态和错误信息,不过这也不是必须的。然后,把整个 #commentform 和附属的元素用一个大的 div 包进来,ID 设为 #commentformbox,…… 你猜对了,这一步仍然不是必须的,我们做这么多不过是为了迎合下面的 jQuery 脚本,我在这里贴出来的可能只直接适用于自己的主题,但是如果你能够看得懂下面的代码,那么你也明白怎么样把这些代码改为适合自己的。 :lol:

实现相应的 jQuery 代码:comments.js

jQuery 提供了 jQuery.ajax API,使用起来相当简便,在这里,我们需要用到的参数有 String url, Object data, String type, Function beforeSend, Function error, Function success,前三个参数用来定义 Ajax 请求的地址、数据、请求类型,后三个函数用来给发送请求之前、发生错误和请求成功添加处理动作。

以下是代码(借鉴于同样很好很强大的 K2 主题,并做了部分修改):

if ($('#commentform').length) {
    $('#commentform').submit(function(){
        jQuery.ajax({
            url: 'comments-ajax.php', // 这里要改为 comments-ajax.php 文件的位置
            data: $('#commentform').serialize(), // 从表单中获取数据
            type: 'POST', // 设置请求类型为 ‘POST’,默认为 ‘GET’
            beforeSend: function() {
                $('#commenterror').hide();
                $('#commentload').show();
            },
            error: function(request) {
                $('#commentload').hide();
                $('#commenterror').show().html(request.responseText);
            },
            success: function(data) {
                $('textarea').each(function(){
                    this.value='';
                });
                $('#commenterror').hide().html();
                $('#comments').html(parseInt($('#comments').html()) + 1);
                if (!$('#commentlist').length) {
                    $('#pinglist').before('<ul id="commentlist"></ul>');
                }
                $('#commentlist').append(data); // 追加留言数据
                $('#commentform :input').attr('disabled', true);
                $('#commentformbox').fadeOut(1000);
                $('#commentload').hide();
                setTimeout(function() { // 提交留言 15 秒后方可再次提交新留言
                    $('#commentform :input').removeAttr('disabled');
                    $('#commentformbox').fadeIn(1000);
                }, 15000);
            }
        });
        return false;
    });
}

编写 comments-ajax.php

这个文件就是我们刚才写好的 jQuery 代码请求的链接,用来把从 #commentform 表单中得到的信息添加至 WP 数据库中。下面这段代码是直接从 K2 主题中 COPY 过来的(感谢 K2 的数位作者!),需要注意的是,最后一部分的 li 元素(对应于一条留言)需要修改到与你自己的 comments.php 相适应:

<?php
if ($_SERVER["REQUEST_METHOD"] != "POST") {
    header('Allow: POST');
    header("HTTP/1.1 405 Method Not Allowed");
    header("Content-type: text/plain");
    exit;
}
$db_check = true;
function kill_data() {
    return '';
}
function check_db() {
    global $wpdb, $db_check;
    if($db_check) {
        // Check DB
        if(!$wpdb->dbh) {
            echo('Our database has issues. Try again later.');
        } else {
            echo('We\'re currently having site problems. Try again later.');
        }
        die();
    }
}
ob_start('kill_data');
register_shutdown_function('check_db');
require_once(dirname(__FILE__)."/../../../wp-config.php");
$db_check = false;
ob_end_clean();
nocache_headers();
function fail($s) {
    header('HTTP/1.0 500 Internal Server Error');
    echo $s;
    exit;
}
$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) ) {
    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('Sorry, you must be logged in to post a comment.');
}
$comment_type = '';
if ( get_option('require_name_email') && !$user->ID ) {
    if ( 6> strlen($comment_author_email) || '' == $comment_author )
        fail('Error: please fill the required fields (name, email).');
    elseif ( !is_email($comment_author_email))
        fail('Error: please enter a valid email address.');
}
if ( '' == $comment_content )
    fail('Error: please type a comment.');
// 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('Duplicate comment detected; it looks as though you\'ve already said that!');
}
$commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'user_ID');
$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'));
$comment->comment_type = 'comment';
$comment_index = $_POST['comment_count'] + 1;
?>
<li id="comment-<?php echo $comment->comment_ID; ?>">
<!-- 这里需要添加你的代码 -->
</li>

收尾工作及测试

上面的工作做完后,把这几个文件存在当前主题所在目录下面,记得在 header.php 中引入 jQuery 框架和你刚才写好的 comments.js,否则留言功能是不起作用的哦。在浏览器中按下 Ctrl + F5 重新加载你的 blog 日志后,写几句话提交,是不是已经变成 Ajax 的了?留言提交成功后,留言框 #commentformbox “淡出”的效果看到了么,过 15 秒后它又会“淡入”。

嗯,对了,你也发现了,在点击提交留言的按钮之后,如果没有一个不断旋转的动画图标  表达“正在提交”,肯定不够过瘾,那我们来把它加上,把这个图标另存到你的主题所在目录下的 images 目录下(绕口令),然后打开 style.css 在其中加上一句:

#commentload {
display: none;
height: 18px;
width: 18px;
background: url('images/spinner.gif') no-repeat center center;
}

当然,如果觉得这个动画图标不好看,你可以到这里生成你最中意的。

结束语

行了,就写这么多吧,漏了什么等发现了再补。我的感受:偶尔尝试一下不靠插件自己动手实现自己想要的功能,其实也蛮过瘾!动手之前想试试效果吗?给我留个言试试吧 :lol:

收藏和分享:

我来说两句

用户名: 新注册) 密码: 匿名评论 [所有评论]
评论内容:不能超过250字,请留下您的联系方式,方便我们回复您的留言。

网站地图 - 关于我们 - 版权声明 - 广告服务 - 联系我们 - 诚聘英才 - 帮助中心
Copyright © 2007-2008 www.blog286.com all Right Reserved
博客学堂 版权所有