Php - Ajax喜欢/不喜欢按钮

Sey*_*han 1 php ajax social-media-like

我通过使用喜欢/不喜欢按钮为我的脚本从互联网搜索中找到了这个脚本

http://wcetdesigns.com/view.php?dtype=tutorials&category=php&id=22

使用单一职位时,每个人都能很好地工作,但是,

我希望使用此评级脚本来处理来自周期的所有文档

例如,我有新闻脚本和列出的所有新闻,并且您看到喜欢/不喜欢按钮的标题附近.(像stackoverflow网页),我想分别评价所有这些内容.在这个脚本中,我无法在同一页面中分隔文章ID

你能帮我解决一下吗?

小智 7

首先,您需要为每个按钮指定哪个文章,您可以使用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//?>
Run Code Online (Sandbox Code Playgroud)

现在你需要在点击按钮时做一些事情,所以你的javascript看起来像这样:

$('.votebutton').on("click", function(){
  vote = $(this).attr("data-vote");
  article = $(this).attr("data-article");
  rateArticle(vote, article);
})
Run Code Online (Sandbox Code Playgroud)

现在你需要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); 
     }
   });
}
Run Code Online (Sandbox Code Playgroud)

在服务器端,您将发布到的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;
}
Run Code Online (Sandbox Code Playgroud)

就是这个......