我首先遇到了一个小问题,请忽略我的折旧函数。我正试图连续运行PHP函数。点击时我有一个按钮触发了一个正确运行的Ajax脚本。Ajax页面将类似内容插入到数据库中,但我需要向用户显示,他的类似内容已经计数,但在我重新加载页面之前,类似函数计数脚本不会更新,有没有一种方法可以让我不断地重新加载PHP函数,这样如果有任何新的类似程序进入数据库,它就会更新,提前感谢。
//php function for counting likes functions.php
function likes_count($postid){
set_time_limit(0);
$g = mysql_query("SELECT COUNT(*) FROM postlikes WHERE postid = $postid") or die (mysql_error());
$co = mysql_fetch_array($g);
$count = $co[0];
echo $count;
}
//like button index.php where the image post appears for the user to like
<button style="margin-left:13px;" id="<?php echo $postid;?>" class="col-md-5 n btn btn-default btn-xs like"><i id="f" class="fa fa-thumbs-o-up"></i> <span id="like_<?php echo $postid ?>"><?php echo likes_count($postid); ?> </span> Likes</button>
//
//ajax for calling the like page on index.php
<script>
$('.like').on('click', function (e){
var userid = "<?php echo $ida ?>";
var postid = $(this).attr('id');
if ((postid == "")) {
alert("no info bro");
} else {
$.ajax({
type: "POST",
url: "like.php",
data: {postid: postid, userid: userid},
cache: false,
});
}
e.preventDefault();
});
</script>
//like page it self like.php
<?php
include "connect.php";
mysql_select_db("unilag");
if(isset($_POST['postid'])) {
$postid=$_POST['postid'];
$id=$_POST['userid'];
$e = mysql_query("SELECT * FROM postlikes WHERE userid = $id AND postid = $postid") or die(mysql_error());
if(mysql_num_rows($e) > 0) {
// remove like&
$re = mysql_query("DELETE FROM postlikes WHERE userid = $id AND postid = $postid") or die (mysql_error());
$notify = mysql_query("DELETE FROM notification WHERE nfrom = $id AND type = 'like_post' AND postid = $postid") or die (mysql_error());
} else {
// like post
$re = mysql_query("INSERT INTO postlikes SET userid = $id, postid = $postid, date = now()") or die (mysql_error());
$rr = mysql_query("SELECT userid FROM post WHERE post_id = $postid");
$y = mysql_fetch_array($rr);
$iii = $y['userid'];
$notify = mysql_query("INSERT INTO notification SET nfrom = $id, nfor = $iii, type = 'like_post', postid = $postid, seen = 'no', date = now()") or die (mysql_error());
}
echo likes_count($postid);
}
?>
$('.like').on('click', function (e){
var userid = "<?php echo $ida ?>";
var postid = $(this).attr('id');
if ((postid == "")) {
alert("no info bro");
} else {
$.ajax({
type: "POST",
url: "like.php",
data: {postid: postid, userid: userid},
cache: false,
}).then(function(count){
$(".like-"+postid).text(count);
});
}
e.preventDefault();
});
您的like.php echo超出了点赞数,但您没有使用该值执行任何操作。在ajax调用中添加一个成功回调,并更新包含相同计数的元素
$.ajax({
type: "POST",
url: "like.php",
data: {
postid: postid,
userid: userid
},
cache: false
}).then(function(count){
$("#like_"+postid).text(count);
});
附带说明一下,您有echo likes_count($postid);
,但您的函数不返回任何内容,因此没有任何内容可回显,您已经回显了函数中的值。因此,在likes_count($postid)
之前不需要echo