我正在使用 AJAX 和 PHP 开发投票系统,但遇到了一些麻烦。我们正在显示数据库中的一堆帖子,每个帖子旁边都有一个图像 - 单击图像应该 1) 切换图像颜色,然后 2) 使用 AJAX 调用 PHP 脚本,然后决定是否添加或减去一票。我的图像切换工作正常,但我不确定如何进行下一部分。最好的方法是什么?
这是输出帖子的 while 循环:
while($row = mysql_fetch_array($result))
{
?>
<li class = "post">
<a href = "#" onclick = "return toggle(this,'heart<?php echo $row['post_id'];?>')"><img name = "heart<?php echo $row['post_id'];?>" src = "/images/heart.png" class = "thumbnail" width = "15" /></a>
<p class = "title"><img class = "favicon" width = "16" height = "16" src = "<? echo $row['favicon']; ?>" /><a href = "<? echo $row['post_url']; ?>" target = "_blank"><? echo $row['post_title']; ?></a></p>
<p class = "postinfo">posted <? echo doRelativeDate( $row['date'] ); ?> by <a href = "<? echo $row['blog_url'];?>"><? echo $row['blog_name']; ?></a>
</li>
<?
}
?>
最佳答案
"src = "/images/heart.png"class = "thumbnail"width = "15"id="voteImage
/>
向您的图像添加一个 ID。通过任何 JavaScript 框架捕获此 Id 上的点击事件。
我给出了 jQuery 的例子。
jQuery("#voteImage").live("click",function(){
var imageName = jQuery(this).attr('name');
var postId = imageName.substr(5); //Here you will have post Id because remove heart from heart20
//now you can hit ajax call to your vote-up or vote-Down php with postId
jQuery.ajax({
type: 'POST',
url: baseURI+'voteup.php',
data:"postId="+postId,
cache: false,
success: function(result)
{
//perform further action like give alert to user that action performed
}
});
}
关于php - AJAX+PHP投票系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3604953/