【发布时间】:2017-05-08 13:19:22
【问题描述】:
我想用 PHP 和 jQuery/AJAX 制作喜欢/不喜欢的系统..
这是我在 PHP foreach 中的表单...这里我为每个表单都有自己的 ID;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
这是我的 Ajax 脚本;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
- 代码工作但不正确;
- 当我点击“赞”按钮运行良好时,我检查了数据库,计算、插入、删除,运行良好...
- 但是我想用 AJAX 来做这个,因为如果用户点击喜欢按钮,刷新页面会在用户观看视频时停止视频。由于页面刷新,视频正在预加载...
- 在我添加我的 ajax 脚本后,它就可以工作了。但是当我点击like按钮时,AJAX正在发布到PHP,只有foreach循环中的最后一个id,
问题? 如何让 AJAX 获取 PHP foreach 循环中的所有 id?
如果你想查看,这是我的 videolike.php;
<?php
session_start();
if($_POST['id'] && @$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
【问题讨论】:
-
尝试通过更改
.click侦听器和函数开始来停止浏览器默认执行:$('.classform').on('click', 'button.submitbuttonclass', function(e) { e.preventDefault(); [... rest of function] });(也使用$(this).serialize()而不是$('.class').serialize())我认为您错过了停止默认执行,因此您在服务器端获得的结果不是来自您的$.ajax()函数的结果。另外,您提到了一个 php foreach() 循环。但是,您的示例中没有。
标签: javascript php jquery ajax