向节点发送ajax请求后无需重新加载页面即可更新ejs中的视图

问题描述 投票:0回答:1

我有一个购物车,其购物车的数量字段包含加号按钮,用户可以单击加号按钮以增加数量。我一直在寻找一种无需重新加载页面即可更新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 VIEW

   <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
1个回答
0
投票

我发现它没有更新,因为我也没有更新包含该值的输入字段includes / totalPrice.ejs

<span id="price_span" class="price text-right">Ksh. <%=subTotal %></span>
<input type="hidden" name="totalPrice" id="totalPrice" value="<%=subTotal %>">

然后我用div包裹了span和输入

   <div id="total_div" class="total-price border">
      <span id="price_span" class="price text-right">Ksh. <%=cake.price %></span>
      <input type="hidden" name="totalPrice" id="totalPrice" value="<%=cake.price %>">
   </div>

然后终于在ajax request函数中,我将updateDOM函数从获取范围的ID更改为获取该total_div的ID

var updateDOM = function (result) {
  var totalPrice_div = document.getElementById("total_div");

  totalPrice_div.innerHTML = result;
};

:))

© www.soinside.com 2019 - 2024. All rights reserved.