首先,你需要指定不同的按鈕,這條是它,你可以很容易地與數據 - 屬性
<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看起來這樣的事情:
$('.votebutton').on("click", function(){
vote = $(this).attr("data-vote");
article = $(this).attr("data-article");
rateArticle(vote, article);
})
現在你需要的rateArticle()函數會是這個樣子:
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文件看起來是這樣的:
$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;
}
而且僅此而已......
肯定。你有什麼,你有什麼嘗試,什麼不適合你? –
我確實成功對單個帖子進行評分,我沒有對單獨列出的一頁中的帖子進行評分。腳本只是率先發布。我想要做像stackoverflow一樣的想法。帖子和答案列在頁面中,每個人都可以通過點擊贊或不喜歡按鈕來評價每篇文章 – Seyhan