无法使用jquery ajax实现follow-unfollow按钮

时间:2017-06-29 19:18:45

标签: javascript php jquery html ajax

场景:follow和unfollow操作的数据库部分工作正常。 jquery和ajax部分必定存在一些问题,因为只有在刷新页面而不是单击后,按钮才会从关注更改为取消关注(几乎没有css样式)。如果没有刷新,则无法多次单击该按钮。这是jquery部分

<script>
function addfollow(friend,action)   
{
    $.ajax({
        url:"follow.php",
        data:'friend='+friend+'&action='+action,
        type:"POST",
        success:function(data){
            switch(action){
                case "follow":
                $("#"+friend).html('<input type="submit" id="'+friend+'" class="unfollow" value="unfollow" onClick="addfollow('+friend+',\'unfollow\')"/>');
                break;
                case "unfollow":
                $("#"+friend).html('<input type="submit" id="'+friend+'" class="follow" value="follow" onClick="addfollow('+friend+',\'follow\')"/>');
                break;
            }
        }
    });
}
</script>

下面是用于调用上述方法的html + php代码

<?php
    $action="follow";
    if()//php code to check if user is already a follower 
    {
       $action="unfollow";
    }
    $friend=$name;
?>
<div class="col-sm-12">
    <input type="submit" id="<?php echo $friend;?>" class="<?php echo $action;?>" value="<?php echo $action?>" onClick="addfollow('<?php echo $friend;?>','<?php echo $action;?>')"> 
</div>

因为,我对jquery-ajax没有正确的理解,所以我认为在sucess:function(data)中的语法一定有问题。 ħ

1 个答案:

答案 0 :(得分:0)

jQuery.html()。将得到/设置匹配的元素的html INSIDE。这不是你想要的。尝试.replaceWith()删除当前元素并将其替换为其他元素。

编辑:

如果你采用更加以javascript为中心的方法,你也可能会有更好的运气。用php编写javascript会让人感到困惑。

如果你的php代码刚刚创建了类似的元素。

<button> data-friend-id="<?php echo $friend;?>" class="follow-button <?php echo $action;?>" data-following="true"></button>

然后你可以在javascript中处理其余的逻辑。类似的东西:

//Set a click handler on the follow buttons.
$('.follow-button').click(handleFollowClick);

function handleFollowClick() {
  var $button, friend_id, action;    

  // jQuery will set 'this' to the button that was clicked. 
  $button = $(this);

  // Extract data from the button.
  friend = $button.data('friend-id');
  action = $button.data('following') === 'true' ? 'unfollow' : 'follow';

  $.ajax({
    url:"follow.php",
    data:'friend='+friend+'&action='+action,
    type:"POST",
    success:function(data){ toggleFollow($button)}
  });
}

//You could actually get away with styling the button default as
//not-following. Then just $button.toggleClass('follow'); but
//this is consistent with your existing approach.
toggleFollow($button) {
  if ($button.data('following') === 'true) {
    $button.data('following', 'false');
    $button.removeClass('unfollow');
    $button.addClass('follow');
  } else {
    $button.data('following', 'true');
    $button.removeClass('follow');
    $button.addClass('unfollow');
  }
}
相关问题