gpt4 book ai didi

javascript - 单击按钮如何运行 php 脚本

转载 作者:行者123 更新时间:2023-11-28 04:28:16 25 4
gpt4 key购买 nike

我是 PHP 初学者。我想向喜欢按钮添加功能。每当用户单击“like”按钮时,就会运行插入查询以在数据库中插入值。首页有多个图片,相应的产品图片信息(productid)必须插入到product_likes db中。`

     <?php
$user_name=$_SESSION['user_name'];
$query="SELECT * FROM product_info";
$result= mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result)) {


?>
<div class="w3-container"><br>
<img src="<?php echo "img/product_img/".$row['productimage'].""; ?>">
<p><b>Product Name: </b><?php echo"".$row["productname"].""?><br>
</p>
<form id="like" method="post" action="home1.php">
<button type="submit" name="like"><i class="fa fa-heart"></i>  Like</button>
<?php
if(isset($_POST['like'])){
$result=mysqli_query($con,"INSERT INTO product_likes VALUES ('','".$row['productid']."','".$row1['sellerid']."','".$buyerid."')");

}
?>
</form>
</div>
<?php } ?>`

但是每当我运行此命令时,与第一张图像对应的相同的productid、sellerid和buyerid都会插入数据库中,并且仅显示第一张图像。有办法解决这个问题吗?

最佳答案

您需要了解的第一件事是,PHP 是服务器端语言,在客户端之前执行,而 JavaScript 是客户端语言,在服务器端完成处理后执行,并且不会返回到服务器。

当您想要执行诸如根据用户行为与服务器对话之类的操作时,您需要配置一个端点并向服务器发起 AJAX 调用。使用 jQuery 点赞帖子的简单示例是:

$(function() {
$("a").click(function(e) {
e.preventDefault();
$this = $(this);
if ($(this).text().trim() == "Like") {
$.post("/posts/like", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Unlike");
});
$this.text("Unlike");
} else {
if ($(this).text().trim() == "Unlike") {
$.post("/posts/unlike", {
PostID: 1
}, function(res) {
if (res == "success")
$this.text("Like");
});
$this.text("Like");
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Like</a>

由于有回退,上面的示例有点“有效”,但这几乎就是概念。制作“喜欢”或“不喜欢”的整个 PHP 代码应该单独给出,并且使用 jQuery 的 AJAX 功能,您需要将其关闭。

上述两个 URL:/posts/unlike/posts/like 均采用数据参数 PostID 并据此生成对数据库进行必要的更改。

关于javascript - 单击按钮如何运行 php 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44849113/

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