【问题标题】:Update my view in ejs after sending an ajax request to node without reloading page在向节点发送 ajax 请求而不重新加载页面后更新我在 ejs 中的视图
【发布时间】: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


    【解决方案1】:

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

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

    然后我用 div 包装了 span 和 input

       <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请求函数中,我将updateDOM函数从获取span的id改为获取那个total_div的id

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

    :))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-26
      • 2021-06-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 2020-09-07
      相关资源
      最近更新 更多