【发布时间】:2020-06-17 15:16:19
【问题描述】:
我有一个购物车,其中有一个数量字段,其中包含一个加号按钮,用户可以单击该按钮来增加数量。
我正在寻找一种无需重新加载页面即可更新 DOM 的方法。
我今天发现了 AJAX 请求,并且我设法编写了这样的代码:如果用户单击 add(+) 按钮,单价就会添加到总价格中并显示出来。
我的问题是这仅在第一次尝试时有效,但在随后的点击中 UI 不会更新。
Ajax 脚本:
$("#plus_btn").on("click", function (event) {
event.preventDefault();
event.stopPropagation();
var onekg = document.getElementById("onekg").value;
var totalPrice = document.getElementById("totalPrice").value;
var data = {};
data.onekg = onekg;
data.totalPrice = totalPrice;
$.ajax({
url: "/update-shopping-cart",
type: "POST",
data: data,
})
.done(function (result) {
updateDOM(result);
})
.fail(function (err) {
console.log(err);
});
});
var updateDOM = function (result) {
var totalPrice_div = document.getElementById("price_span");
totalPrice_div.innerHTML = result;
};
EJS 视图
<h1>$ 1000</h1>
//Unit price of item
<input type="hidden" name="onekg" id="onekg" value="1000">
<button id="plus_btn" type="button" name="button">+</button>
//Total price to be updated and displayed on the DOM
<span id="price_span" >$ 1000</span>
<input type="hidden" name="totalPrice" id="totalPrice" value="1000">
routes.js
router.route("/update-shopping-cart").post((req, res) => {
console.log(req.body);
let totalPrice = parseInt(req.body.totalPrice) + parseInt(req.body.onekg);
res.status(200);
res.render('includes/totalPrice', {
subTotal: totalPrice
});
res.end();
});
includes/totalPrice.ejs - 更新 DOM 的 ejs 模板
<span id="price_span">Ksh. <%=subTotal %></span>
【问题讨论】:
标签: javascript node.js ajax ejs