[英]Cannot implement follow-unfollow button using jquery ajax
方案:關注和取消關注操作的數據庫部分運行正常。 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)的語法中肯定有問題。 H
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');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.