gpt4 book ai didi

php - ajax 喜欢/不喜欢按钮不切换回来

转载 作者:行者123 更新时间:2023-12-01 03:46:39 27 4
gpt4 key购买 nike

我正在尝试在页面上制作一个“赞”按钮,但似乎无法使其正常工作。基本上有三个函数使用ajax将数据发送到更新数据库的php页面。我已经检查了数据库并且所有三个更新都正确。如果用户最初不喜欢并单击,它会正确显示“不喜欢”按钮,但如果您单击“不喜欢”,它不会切换回来(尽管它会更新数据库)。

这是设置的正确方法吗?我对 ajax 还很陌生,不确定这是否是正确的方法。提前致谢史蒂夫

public function likesScript($p){?>
<script>

//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {


//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');

$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');

}

$("#likedBy").append(res);
console.log(res);

});
}


function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})

getLikes();


return false;
}


function addLike() {


$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})


getLikes();


return false;
}



$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);


});



</script>

likelist.php:

<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';

$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';

$profile = new profile($dbh);

if(isset($_POST)){
$p = $_POST['p'];


$view->printLikes($profile->getLikes($p));


}

likedata.php:

<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';

$profile = new profile($dbh);

if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];

$profile->insertLikes($liker, $likee, $likeYesNo);


}
?>

最佳答案

AJAX 是 ayshcronous,因此 getLikes 函数将在 addLikeremoveLike 中的 AJAX 完成之前触发。您绝对需要将 getLikes 放入 $.ajax 的成功回调中,这样它就不会检索可能尚未更新的数据

function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})

}

关于php - ajax 喜欢/不喜欢按钮不切换回来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187615/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com