我正在尝试创建一个简单的喜欢/不喜欢按钮来更新数据库。jQuery 代码位于外部文件中。PHP 变量是从 Codeigniter 中的控制器发送的。
当页面重新加载时,它会正确显示当前登录的用户是否能够喜欢或不喜欢他们正在查看的用户。如果他们单击一次,一切正常 - 按钮在喜欢/不喜欢之间变化,喜欢的数量增加或减少,并且数据库被更新。第二次单击时,它会重新加载整个页面但不更新数据库 - 我如何停止刷新 + 使其在不重新加载页面的情况下更新?
PHP:
<div id="like_button">
<p><a href=""><span id="like_unlike" class="link"><?php if($already_liked){echo "Unlike";}else{echo"Like";}?></span></a> (<span id="number_of_likes"><?php echo $number_of_likes; ?></span>)</p>
<span id="liked_unliked_user_id" style="display:none"><?php echo $liked_unliked_user_id; ?></span>
<span id="liking_unliking_user_id" style="display:none"><?php echo $liking_unliking_user_id; ?></span>
</div>
jQuery:
$( function() {
$( '#like_button a' ).click( function( e ) {
var thisrecord = $( this ).closest( "div" );
var liking_unliking_user_id = parseInt( thisrecord.find( "span#liking_unliking_user_id" ).html() );
var liked_unliked_user_id = parseInt( thisrecord.find( "span#liked_unliked_user_id" ).html() );
var like_unlike = thisrecord.find( "#like_unlike" ).html();
if (like_unlike == 'Like')
{
$( this ).replaceWith( '<a href=""><span id="like_unlike" class="link">Unlike</span></a>' );
var likes = parseInt( thisrecord.find( "span#number_of_likes" ).html() ) + 1;
thisrecord.find( "span#number_of_likes" ).html( likes );
$.post( base_url+"/controller/function/" + liked_unliked_user_id + "/" + liking_unliking_user_id );
}
else
{
$( this ).replaceWith( '<a href=""><span id="like_unlike" class="link">Like</span></a>' );
var likes = parseInt( thisrecord.find( "span#number_of_likes" ).html() ) - 1;
thisrecord.find( "span#number_of_likes" ).html( likes );
$.post( base_url+"/controller/function/" + liked_unliked_user_id + "/" + liking_unliking_user_id );
}
e.preventDefault();
});
});