跳到主要内容

ajax实现文章顶踩:喜欢还是不喜欢

本篇应用教程要实现的内容为文章定踩功能,或者说“喜欢”“不喜欢”。
实现步骤:
本实例以上图所示喜欢和不喜欢为例。

一、新建数据表

新建数据表,将文章投票数据保存在新的数据表中,我们需要记录用户ID,文章ID,投票内容,用户ip,新数据表如下:

/*********更新重写规则***************/
function ashu_load_theme() {
    global $pagenow;
    if ( is_admin() && 'themes.php' == $pagenow && isset( $_GET['activated'] ) )
        ashu_vote_install(); //激活主题的时候执行函数
}
add_action( 'load-themes.php', 'ashu_load_theme' );
function ashu_vote_install(){
    global $wpdb;
    //创建 _post_vote表
    $table_name = $wpdb->prefix . 'post_vote';
    if( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name ) :
    $sql = " CREATE TABLE `".$wpdb->prefix."post_vote` (
      `id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
      `user` INT NOT NULL ,
      `post` INT NOT NULL ,
      `rating` varchar(10),
      `ip` varchar(40)
     ) ENGINE = MYISAM DEFAULT CHARSET=utf8;";
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    endif;
}

二、准备投票和查询函数

准备数据库操作函数,包括添加数据函数和查询数据,将如下函数代码也添加到主题的functions.php文件(或自定):

1、添加数据函数
/*
*添加投票函数
*$post_id 文章id
*$user_id 用户ID
*$ip 用户IP
*$rating 投票内容
*/
function add_vote($post_id,$user_id='',$ip='',$rating='up'){
    global $wpdb;
    $user_id = (int)$user_id;
    $post_id = (int)$post_id;
    if(($user_id=='')&&($ip=='')){
        return "e"; //返回error
    }
    //检查用户对某一文章是否已经投票票了
    if($user_id!=''){
        $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and user='$user_id'";
    }else{
        if($ip!=''){
            $check= "select * from ".$wpdb->prefix."post_vote where post='$post_id' and ip='$ip'";
        }
    }
    $coo = $wpdb->get_results($check);
    //投票内容只能是up或者down
    if($rating=='up'){
        $rating='up';
    }else{
        $rating='down';
    }
    //如果不存在数据
    if(!count($coo) > 0){
        //插入数据 sql
        $s = "insert into ".$wpdb->prefix."post_vote (user,post,rating,ip) values('$user_id','$post_id','$rating','$ip')";
        $wpdb->query($s);
        return "y"; //返回yes
    }else{
        return "h"; //返回have
    }
    return "e";//返回error
}
2、查询投票数据函数

比如查询某文章点击up的数据,则使用 get_post_vote(1,’up’);

/*
*获取文章投票数据
*$post_id 文章ID
*$vote 投票内容
*/
function get_post_vote($post_id,$vote='up'){
    global $wpdb;
    $post_id = (int)$post_id;
    if($vote == 'up'){
        $vote='up';
    }else{
        $vote='down';
    }
    //查询数据sql
    $sql = "select count(*) from ".$wpdb->prefix."post_vote where post='$post_id' and rating='$vote'";
    $coo = $wpdb->get_var($sql);
    if($coo)
    return $coo; //返回数据
    else
    return 0;
}

三、准备前台html和js

建立好了新的数据表,也准备好了实现投票功能的函数,接下来看前台的html和js。
1、网页前台显示数据,将下面的代码放在输出文章的循环内,即常说的loop中。

<span class="vote_up" id="<?php echo 'vote_up'.$post->ID;?>">
    <a href="javascript:void(0);" rel="<?php echo 'up_',$post->ID;?>">
    <span id="<?php echo 'vup'.$post->ID;?>">
        <?php echo get_post_vote($post->ID,'up');?>
    </span>
    </a>
喜欢-顶!</span>
<span class="vote_down" id="<?php echo 'vote_down'.$post->ID;?>">
    <a href="javascript:void(0);" rel="<?php echo 'down_'.$post->ID;?>">
    <span id="<?php echo 'vdown'.$post->ID;?>">
        <?php echo get_post_vote($post->ID,'down');?>
    </span>
    </a>不喜欢-踩!
</span>

上面代码将会输出一个如下的html结构

<span class="vote_up" id="vote_up44">
    <a href="javascript:void(0);" title="值得" rel="up_44">
    <span id="vup44">
        0
    </span>
    </a>
喜欢-顶!</span>
<span class="vote_down" id="vote_down44">
    <a href="javascript:void(0);" title="不值" rel="down_44">
    <span id="vdown44">
        1
    </span>
    </a>不喜欢-踩!
</span>

四、js代码

本篇教程中和上一篇一样,我们同样使用jquery发起ajax请求,所以首先在网页头部加载jquery代码,我在主题底部文件footer.php中加载jqeury。我将jquery-1.7.2.min.js放在了主题文件夹的js文件夹里面,所以用get_template_directory_uri()函数来输出主题的url

<script src="<?php%20echo%20get_template_directory_uri();?>/js/jquery-1.7.2.min.js"></script>

然后我将发起ajax请求代码也放在了主题里面js文件夹中的likeornot.js文件,所以再加上一个
其中输出了ajax请求的地址:web.mgsh.co/wp-admin/admin-ajax.php

<script type="text/javascript">var ajax_url = '<?php echo admin_url(); ?>admin-ajax.php';</script>
<script src="<?php%20echo%20get_template_directory_uri();?>/js/likeornot.js"></script>

likeornot.js文件中的代码

/**
 * author:ashuwp
 * URI: web.mgsh.co
 */
/**
 * 获取Cookie
 *name  cookie名称
 */
function getCookie(name) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
        return null;
    if ( start == -1 )
        return null;
    var end = document.cookie.indexOf( ';', len );
    if ( end == -1 )
        end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}
function ashu_isCookieEnable() {
    var today = new Date();
    today.setTime( today.getTime() );
    var expires_date = new Date( today.getTime() + (1000 * 60) );
    document.cookie = 'ashu_cookie_test=test;expires=' + expires_date.toGMTString() + ';path=/';
    var cookieEnable = (getCookie('ashu_cookie_test') == 'test') ?  true : false;
    //document.cookie = 'ludou_cookie_test=;expires=Fri, 3 Aug 2001 20:47:11 UTC;path=/';
    return cookieEnable;
}
jQuery(document).ready(function($) {
    var ashu_token = 1;
    $('.vote_up a').click(function(){
        //检查浏览器是否启用cookie功能
        if( !ashu_isCookieEnable() ) {
            alert("很抱歉,您不能给本文投票!");
            return;
        }
        if( ashu_token != 1 ) {
            alert("您的鼠标点得也太快了吧?!");
            return false;
        }
        ashu_token = 0;
        //获取投票a标签中的rel值
        var full_info = $(this).attr( 'rel' );
        var arr_param = full_info.split( '_' ); //以字符"_"分割
        //发起ajax
        $.ajax({
            url:ajax_url, //ajax地址
            type:'POST',
            //请求的参数包括action   rating  postid三项
            data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],
            //返回数据
            success:function(results){
                if(results=='n'){
                    alert('评价失败');
                    ashu_token = 1;
                }
                if (results=='y'){
                    //如果成功,给前台数据加1
                    var upd_vd = 'vup' + arr_param[ 1 ];
                    $('#'+upd_vd).text(parseInt($("#"+upd_vd).text())+1);
                    ashu_token = 1;
                }
                if (results=='h'){
                    ashu_token = 1;
                    alert('已经发表过评价了');
                }
                if (results=='e'){
                    ashu_token = 1;
                    alert('评价失败');
                }
            }
        });
    });
    $('.vote_down a').click(function(){
        if( !ashu_isCookieEnable() ) {
            alert("很抱歉,您不能给本文投票!");
            return;
        }
        if(ashu_token != 1) {
            alert("您的鼠标点得也太快了吧?!");
            return false;
        }
        ashu_token = 0;
        var full_info = $(this).attr( 'rel' );
        var arr_param = full_info.split( '_' );
        $.ajax({
            url:ajax_url,
            type:'POST',
            data:'action=vote_post&rating=' + arr_param[ 0 ] + '&postid=' + arr_param[ 1 ],
            success:function(results){
                if(results=='n'){
                    alert('评价失败');
                    ashu_token = 1;
                }
                if (results=='y'){
                    var upd_vd = 'vdown' + arr_param[ 1 ];
                    $("#"+upd_vd).text(parseInt($("#"+upd_vd).text())+1);
                    ashu_token = 1;
                }
                if (results=='h'){
                    ashu_token = 1;
                    alert('已经发表过评价了');
                }
                if (results=='e'){
                    ashu_token = 1;
                    alert('发生未知错误');
                }
            }
        });
    });
});

五、后台php处理代码。

在前面的教程中,我们的ajax请求地址直接是网站页码地址,但是本篇教程中,我们的ajax请求地址是类似:web.mgsh.co/wp-admin/admin-ajax.php
使用这个地址来处理ajax请求,请一定记得请求中需要有action参数,然后我们只需要在functions.php文件(或自定)中添加下马代码,即可处理我们的请求,注意执行完请求输出内容之后,添加die函数结束:

/*
*wp的ajax都可以通过请求中的action参数来执行对应的钩子
*示例中我们的action参数值是vote_post
*所以我们可以直接用下面两个钩子来执行动作
*/
add_action("wp_ajax_vote_post", "add_votes_options");
add_action("wp_ajax_nopriv_vote_post", "add_votes_options");
function add_votes_options() {
if( isset($_POST['action']) && ($_POST['action'] == 'vote_post') ){
    $postid = (int)$_POST['postid'];
    if( !$postid ){
        echo 'e'; //输出error
        die(0);
    }
    //cookie中是否已经存在投票数据
    $voted = $_COOKIE["smzdm_voted_".$postid];
    if( $voted ){
        echo 'h'; //输出have
        die(0);
    }
    $ip = $_SERVER['REMOTE_ADDR'];//ip
    $rating = $_POST['rating']; //投票内容
    //判断用户是否登录
    if(  is_user_logged_in() ){
        global $wpdb, $current_user;
        get_currentuserinfo();
        $uid = $current_user->ID;
    }else{
        $uid='';
    }
    if($rating=='up'){
        $rating='up';
    }else{
        $rating='down';
    }
    //添加数据
    $voted = add_vote($postid,$uid,$ip,$rating);
    if($voted=='y'){
        //设置cookie
        setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');
        echo 'y';//输出yes
        die(0);
    }
    if($voted=='h'){
        //设置cookie
        setcookie("ashu_voted_" . $postid,$rating, time() + 3000000, '/');
        echo 'h';
        die(0);
    }
    if($voted=='e'){
        echo 'n';//输出no
        die(0);
    }
}else{
    echo 'e';//输出eroor
}
die(0);
}

六、结束

本票教程并非实现定踩或喜欢功能的最佳选择,只是提供一个ajax的简单示例…
 
 
 
 

返回顶部