我使用 PHP 构建了一个类似 Twitter 的关注/取消关注系统。现在我想使用 AJAX/JQUERY 在后台运行 follow-unfollow PHP 脚本,以避免在关注/取消关注用户时刷新页面。为了让事情变得更简单,我在这里仅使用“取消关注”的例子。正如您所注意到的,我正在运行迭代来输出数据库中的所有成员。我在这里(也是为了简单起见)仅输出成员的姓名和每个成员的取消关注按钮。
这是使用 php 的代码。
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<a href="follow_actions.php?unfollow_id=<?php echo $member->id; ?>"><p class="follow_button">Unfollow</p></a>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
我试图在后台运行 unfollow.php 以获得相同的结果,以避免任何刷新。这是我想出来的,正如你可能想象的那样,它不能正常工作。我将 Jquery 脚本包含在迭代中,我认为这是获取 $member->id
属性然后将其分配给 Jquery 变量的唯一方法。
members.php 尝试使用 AJAX JQUERY 运行脚本的新版本
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
您能为我提供任何帮助吗? 提前致谢。
最佳答案
请记住,在 HTML 中,id 属性必须是唯一的。
由于您要在单个页面上呈现多个成员,因此不应在 jQuery 中使用 id 选择器,而应使用类选择器(例如 button.unfollow
)。如果您使用#unfollow
,您将遇到每个成员按钮之间的 ID 冲突。
首先,使用不带 id 的取消关注按钮呈现所有成员。我使用名为 data-member_id
的数据属性在标记中添加 member_id。
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
然后为所有 button.follow
按钮添加一个单击处理程序,该处理程序从单击的按钮的 data-member_id
属性中提取 member_id
并将其发送到服务器。
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
顺便说一句,您可能应该考虑为此构建一个 RESTful 服务,您可以使用 http://api.jquery.com/jquery.ajax/ 向该服务发布正确的 HTTP 请求。 .
请参阅此处,了解我不久前写的有关 PHP 中 REST 的介绍:
关于javascript - Jquery 和 AJAX 脚本在后台运行 PHP 脚本以避免任何刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33794569/