我有一些帖子和喜欢的代码按钮:
<a href="likes.php?userid='$userid'&postid='$postid'">Like</a>
现在在likes.php中,我有一些针对userid和postid的编码,以找到哪个用户喜欢哪个帖子并将其存储到数据库中。它运行良好但重新加载页面。它转到likes.php,如果它成功,它会回到主页或我想要的任何其他内容。现在我的问题是如何在不重新加载页面的情况下执行此操作,如果我将likes.php代码包含到页面中的帖子和类似按钮。如果有可能,请使用<a ref=""></a>
?或者如果有人有更好的解释,他也可以发布。
答案 0 :(得分:0)
是的,因为您使用了代码ahref
标签,这就是它应该如何工作。如果您不想重新加载尝试使用AJAX。这不是完整的答案,但您需要通过只有ajax。你会发现很多关于它的视频和演示。
检查此示例: http://www.w3schools.com/ajax/ajax_php.asp
<强>更新强>
<强> mainfile.php中强>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<?php
session_start();
$userid=$_SESSION['userid'];
?>
<div id="like">
<a href="#" id="postid" onclick="likeclick(this);">Like</a>
<!-- here id should be different for every post .I would prefer using post id to this ahref id because i would use that to detect what post it is actually. -->
</div>
</html>
<script type="text/javascript">
function likeclick(element)
{
var postid=element.id;
var userid=<?php echo json_encode($userid);?>;
//You can use different methods to pass variable to javascript.I used this one because it is easy to implement
//it has some cons to it .Do check for that on google also.
//http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript
//Check this link for more.
$.ajax({
type:'POST',
url:'getlike.php',
data:{"userid":userid,"postid":postid},
success : function(content)
{
$('#like').html(content);
//This gets the html content from the getlike page and displays in the div on this page.
//Note:I have used .html which replaces any previous content inside the 'like' div.
})
}
</script>
<强> getlike.php 强>
<?php
require 'connect.inc.php'; //This make a connection to the database
$userid=$_POST['userid'];
$postid=$_POST['postid'];
$statement=$mysqli->prepare("select `likes` from `posts` where `postid`=?");
$statement->bind_param("s",$postid);
$statement->execute();
$result=$statement->get_result();
while($row=$result->fetch_assoc())
{
$likes_on_this_post=$row['likes'];
}
$likes_on_this_post=$likes_on_this_post+1; //Added one like more.
$statement=$mysqli->prepare("update `posts` set `likes`=?");
$statement->bind_param("s",$likes_on_this_post);
$statement->execute();
echo "+".$likes_on_this_post;
//This echo is actually the main thing.When this page runs through ajax the response is given back to the calling object
//What goes with response are the html contents on this page as well as whatever i echo on this page.
//Considering this example i have only echoed the no of likes and it doesn't contain any sort of html content so only the echoed element goes.
?>