gpt4 book ai didi

java - 在 JQuery 中使用 ajax 方法 .get() 和 .post() 来添加到购物车

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

我正在做一项作业,我想制作一个“添加到购物车按钮”我尝试了 post 和 get 方法但它什么也没做,代码由 4 个文件组成cart.js 应该允许用户在浏览产品时点击一个链接,它会出现在 cart.html 中

探索.html

<html>
<head>
<title>Digital Waves::Explore</title>
<link rel="stylesheet" href="../css/explore.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="../js/explore.js"></script>
</head>
<body>
<div class="form-group">
<form action="/html/cart" method="POST">
<input name="quantity" type="hidden" value="1" />
<input name="product_id" type="hidden" value="91801160" />
<input name="product_name" type="hidden" value="Red Hat" />
<button class="add-button" type="submit">Add to Cart!</button>
</form>
</div>
</body>
</html>

探索.js

 $(document).ready(function(){
$(".add-button").click(function(){
//alert("explore is clicked");
var productId = $("#productId").val();
var productName = $("#productName").val();
var productQuantity = $("#productQuantity").val();
var data = {
'product_id': productId,
'product_name': productName,
'quantity': productQuantity
};

$.post("html/cart", data, showDone);
var showDone = function() {
alert("I sent the data");
};
});

});

购物车.html

<!DOCTYPE HTML>
<html>
<head>
<title>Digital Waves::Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="../js/cart.js"></script>
</head>
<body>
<button id="buttonx">I get info</button>
<p id="x"></p>
</body>
</html>

购物车.js

$(document).ready(function(){
$("#buttonx").click(function(){
//alert("cart is clicked");
$.get("../html/explore.html",function(data , status){
$("x").html(data);
alert("done");
})
});
});

最佳答案

根据您的 HTML 代码,您没有为输入字段分配 id 属性。您需要使用如下 id 字段:

<div class="form-group">
<form action="/html/cart" method="POST">
<input id="quantity" name="quantity" type="hidden" value="1" />
<input id="product_id" name="product_id" type="hidden" value="91801160" />
<input id="product_name" name="product_name" type="hidden" value="Red Hat" />
<button class="add-button" type="submit">Add to Cart!</button>
</form>
</div>

在此之后,您的 jQuery 代码应该可以正常工作。如果您有多个添加购物车表单,那么您应该使用 class 而不是 id。希望对你有帮助。

关于java - 在 JQuery 中使用 ajax 方法 .get() 和 .post() 来添加到购物车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173288/

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