首先,我搜索过,之前我曾问过这个问题: Creating a Like function php mysql ajax
该线程中的DB问题已解决。我按照说明为AJAX问题创建了第二个版本。
我找到了这个jQuery : Changing class of button with AJAX call,看起来很简单,非常好看。我也遵循了这个http://pluscss.com/tutorials/ajax-like-script-using-php-mysql-jquery教程。但是我遇到了问题并将它们结合起来。
这就是我想要做的事情:
将ajax和like.php作为响应页面(或其他)
我正在尝试创建一个能够返回当前数量的喜欢的功能(我不擅长创建功能,抱歉那个)
function like($post_id,$comment_id)
{
$count = $mysqli->query("SELECT COUNT(*) as TOTAL_COMMENT_LIKES FROM `comments_likes`
WHERE comment_id_fk='".$comment_id."'");
if $row_array=$count->fetch_array(MYSQLI_ASSOC); < 0
then echo "be the first to like"
else
check if user already have liked it
give option to delike
if not have liked
then give option to like
return $TOTAL_COMMENT_LIKES or $TOTAL_POST_LIKE
}
我有两个表,一个用于喜欢的帖子,另一个用于喜欢的评论
CREATE TABLE IF NOT EXISTS `post_likes` (
`like_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`post_id_fk` INT(11),
`uid_fk` int(11) NOT NULL,
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
FOREIGN KEY (post_id_fk) REFERENCES posts(post_id),
FOREIGN KEY (uid_fk) REFERENCES users(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `comment_likes` (
`like_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`comment_id_fk` INT(11),
`uid_fk` int(11) NOT NULL,
`date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
FOREIGN KEY (comment_id_fk) REFERENCES comments(comment_id),
FOREIGN KEY (uid_fk) REFERENCES users(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
最重要的是AJAX:
function like(_element){
if($(_element).hasClass('unlike')){
$.ajax(); //do unlike
$(_element).removeClass('unlike'); // this goes inside the success:function(){} of the ajax call
}else{
$.ajax(); //do like
$(_element).addClass('unlike'); // this goes inside the success:function(){} of the ajax call
}
}
非常感谢所有帮助!