AJAX + PHP投票系统

时间:2010-08-30 23:22:53

标签: php javascript ajax voting

我正在研究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>

    <?
        }
    ?>

1 个答案:

答案 0 :(得分:0)

“src =”/ images / heart.png“class =”thumbnail“width =”15“id="voteImage /&gt;

为您的图片添加一个ID。通过任何javascript框架捕获此Id上的click事件。

我在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
                    }
        });

 }