腓 - 阿贾克斯喜欢/不喜欢按钮 [英] Php - Ajax like / dislike button
问题描述
我发现从互联网上搜索这个脚本中使用喜欢/不喜欢按钮,我的剧本
I found this script from internet search by using like / dislike button for my script
http://wcetdesigns.com/view.php? DTYPE =教程和放大器;类= PHP和ID = 22
万物在使用单岗位工作很好,但是,
Everythings work good when using for single post but,
我想用这个评价剧本的所有文件都来自while循环
I want to use this rating script for all documents come from while cycle
例如,我有新闻脚本,所有的消息都列出来,并靠近标题你看到喜欢/不喜欢的按钮。 (如计算器网页),我想单独评论这所有的内容。在这个剧本,我不能单独文章编号在同一页面
For example, I have news script and all news are listed, and near to title you see like/dislike buttons. (like stackoverflow web page) and I want to rate all this content separately. In this script, I couldn't separate article id's in same page
您可以请帮我一下吗?
推荐答案
首先,你需要为每个按钮,这文章是它,你可以很容易地与数据 - 属性做到这一点。
First, you need to specify for each button which article is it for, you can easily do it with data- attribute
<button class="votebutton" data-article="1" data-vote="1">Up vote</button>
<button class="votebutton" data-article="1" data-vote="-1">Down vote</button>
<span class="votes" data-article="1"><?=//print the current number of votes of this article//?>
现在你需要做的事情是单击该按钮时,让你的JavaScript看起来是这样的:
Now you need to do something when the button is clicked, so your javascript would look something like that:
$('.votebutton').on("click", function(){
vote = $(this).attr("data-vote");
article = $(this).attr("data-article");
rateArticle(vote, article);
})
现在你需要的rateArticle()函数,它看起来是这样的:
now you need the rateArticle() function that would look something like this:
function rateArticle(vote, article){
var data = 'vote='+rating+'&articleID='+article;
$.ajax({
type: 'POST',
url: 'rateArticle.php',
data: data,
success: function(votes){
$('.vote[data-article='+article+']').html(votes);
}
});
}
在服务器端,你会张贴到rateArticle.php文件看起来是这样的:
on the server side, the rateArticle.php file that you'll post to would look something like this:
$vote = $_POST['vote'];
$articleID = $_POST['articleID'];
$currentVotes = ; //fill it with the votes that the article currently have
if($vote != "-1" || vote != "1"){
//goddamn script kids messing with us again, let's put them back where they belong
header("Location: http://www.lemonparty.com"); //probably not this, but you can think of something
}
if(userHasAlreadyVoted()){ //if user has already voted we just return the current number of votes
echo $currentVotes;
}else{
$newVotes = $currentVotes + $vote;
//save newVotes to db...
echo $newVotes;
}
和仅此而已......
And that's about it...
这篇关于腓 - 阿贾克斯喜欢/不喜欢按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!