dougou8552 2013-12-16 03:09
浏览 31
已采纳

使用PHP中的AJAX响应预先填充和覆盖类

I am working on a site that has like button attached to posts made by users. I want whenever a user likes a post, the like count of that post should be replaced with current one but it is affecting the whole post.

This is code for the Like button

echo "<span class = 'likecount'>". $likes . "</span><button class='mlike pacedown' 
 value='".$post_id."' name = 'like' type='submit'><span class = 'buttons'>Like</span>
 <span class='glyphicon glyphicon-heart'></span></button>";

And this the AJAX that gets fired whenever the button is clicked:

$(".mlike").click(function () {
    $(".murconform").submit(function(e){
        return false;
    });
    var post_id = $(this).val();
    var user_id = $(".user_id").text();
    var request = $.ajax({
      url: "likes.php",
      type: "POST",
      data: { post : post_id , user : user_id },
      dataType: "html"
    });
    request.done(function( msg ) {
    alert ("User ID is " + user_id + "  Post ID is " + post_id);              
        $('.likecount').html( msg ); 
    });
});  

And this is the echo result from likes.php after update the database:

echo "<span class = 'likecount'>". $count . "</span>";

The database side is working just fine.

  • 写回答

1条回答 默认 最新

  • doujiao1814 2013-12-16 03:13
    关注

    welll your are replacing the html inside the span with a <span class = 'likecount'> again.

    why don't you just echo $count from you ajax called page and only this will be replaced in success function..

    try this

    in you likes.php file

     echo $count; //just return the count
    

    no changes in ajax ..

    //same
    request.done(function( msg ) {
     alert ("User ID is " + user_id + "  Post ID is " + post_id);              
        $('.likecount').html( msg ); 
    });
    

    that should do the trick..

    you can also change you datatype to JSON and send json as response in your php ..

    updated

     $(".murconform").submit(function(e){
        return false;
     });
    
     $(".mlike").click(function () {
       var $this=$(this);
       var post_id = $(this).val();
       var user_id = $(".user_id").text();
       var request = $.ajax({
           url: "likes.php",
           type: "POST",
           data: { post : post_id , user : user_id },
           dataType: "html"
       });
    
       request.done(function( msg ) {
         alert ("User ID is " + user_id + "  Post ID is " + post_id);              
            $this.prev('.likecount').html( msg ); 
         });
       });  
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部