【问题标题】:how to use ajax in shopping cart session - node js如何在购物车会话中使用 ajax - node js
【发布时间】:2020-03-25 08:22:18
【问题描述】:

我想在我的购物车中插入和删除产品而不刷新页面。我试图在我的代码中使用 ajax,但我不明白我做错了什么。例如,这段代码应该在数据字段中插入一些东西吗?请帮助我解决这个问题

下面是我的 ajax 代码:

$(function() {
  $("#cart_id").click(function(e){
    e.preventDefault();
    var product;
    $.ajax({
        type: "GET",
        data: product,
        url: 'http://localhost:8888/add-to-cart-forward/:id', 
        success: function(response) {
        console.log(response);
        }
      });
  });
});

这是我的节点 JS 代码

  router.get('/add-to-cart-forward/:id', function (req, res, next) {   
      var cart = new Cart(req.session.cart ? req.session.cart : {});

      Product.findById(productId, function (err, product) {
          if (err) throw err;
             cart.add(product, product.id);
                req.session.cart = cart;
                console.log(req.session.cart);
              res.render('shop/description', product);
           });
        });   

【问题讨论】:

  • 在函数 success: function(response) { console.log(response); } 上,您应该在需要查看从 Ajax 调用中获得的响应的网页上进行 DOM 更改。
  • 我尝试将 DOM cganges 转换为成功函数,但我只收到此消息:消息:'Cast to ObjectId failed for value ":id" at path "_id" for model "Product"', name :'CastError',型号:型号{产品}
  • 请编辑问题,并添加您放在success 函数和render() 函数上的代码。我们需要知道渲染返回什么(JSON 代码、XML 代码、纯文本代码……)

标签: javascript arrays node.js ajax cart


【解决方案1】:

已经完成了。它现在的工作。感谢关注。我没有更改我的节点 js 文件,只有 ajax。这是我的ajax代码。

$(document).on('click','#cart_id',function(e){

  e.preventDefault();
  var id = $(this).data('id');
    $.ajax({
        type: "GET",
        data: id,
        url: '/add-to-cart-forward/' + id, 
        success: function() {
          console.log(id)
       }
    });
});

我只是更改了一些字段并分隔了“id”。我希望有人可以使用它

【讨论】:

    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2014-09-14
    • 2011-06-21
    相关资源
    最近更新 更多