繁体   English   中英

当我的购物车仅包含一件商品时,Ajax 没有响应

[英]Ajax is not responding when my cart contains only one item

在我的购物车页面中,当用户选择的产品数量小于一个时,我试图删除一个产品。 这种变化也应该反映在产品总量上。 我为此目的使用 ajax ,它仅在购物车包含多个项目而不是单个项目的情况下删除产品。

1.路线

router.post('/change-product-quantity', (req, res, next) => {
  userHelpers.changeProductQuantity(req.body).then(async (response) => {
   response.total = commaNumber(await userHelpers.getTotalAmount(req.body.user))
   res.json(response)
  })
})

2.changeProductQuantity() function

changeProductQuantity: (details) => {
  details.count = parseInt(details.count)
  details.quantity = parseInt(details.quantity)
  return new Promise((resolve, reject) => {
    if (details.count === -1 && details.quantity === 0) {
      db.get().collection(collection.CART_COLLECTION).
      updateOne({
        _id: objectId(details.cart)
      }, 
      { $pull: { products: { item: objectId(details.product) } }
      }).then((response) => {
        resolve({ removeProduct: true })
      })
    } else {
      db.get().collection(collection.CART_COLLECTION)
        .updateOne({
            _id: objectId(details.cart),
            'products.item': objectId(details.product)
          },
          { $inc: { 'products.$.quantity': details.count }}
        ).then((response) => {
          resolve({ qtyChange: true })
        })
    }
  })
}
    

3.Ajax

function changeQuantity(cartId, proId, userId, count) {
  count = parseInt(count)
  let quantity = parseInt(document.getElementById(proId).innerHTML)
  let qty = quantity + count
  console.log("Qty:" + qty)
  console.log("Count" + count)

  $.ajax({
    url: '/change-product-quantity',
    data: {
      cart: cartId,
      product: proId,
      user: userId,
      count: count,
      quantity: qty
    },
    method: 'post',
    success: (response) => {
      console.log(response)
      if (response.removeProduct) {
        setTimeout(function() { // wait for 5 secs(2)
          location.reload(); // then reload the page.(3)
        }, 5000);
      } else {
        document.getElementById(proId).innerHTML = quantity + count
        document.getElementById('total').innerHTML = response.total
      }
    }
  })
}
    

4.output 屏幕(成功案例和失败案例)

Image1-成功

在此图像中,您可以看到用户的购物车中有多个产品。 当用户更改第二个产品数量时,'qtyChange' object 变为真,而当数量达到零时他/她点击(-)按钮'removeProduct'变为真。 我已经在这张图片的右侧标记了这些更改。

Image2-错误

在这张图片中,您可以看到我试图将数量从 1 减少到零。 在我前面提到的这种情况下,它应该被删除。 但它不会删除。 如上图所示,它不显示 removeProduct object。 当它发生时,我在控制台中收到以下错误。

控制台中的错误

它说总数是未定义的。 为什么会这样? 哪里做错了? 请帮忙..

使用 try catch 并且如果 promise 没有返回响应,则创建自己的响应并返回数据

router.post('/change-product-quantity', async (req, res, next) => {
  try {
    let response = await userHelpers.changeProductQuantity(req.body)
    if(response) {
      response.total = commaNumber(
        await userHelpers.getTotalAmount(req.body.user)
      )
    } else {
      response = {}
      response.total = commaNumber(
        await userHelpers.getTotalAmount(req.body.user)
      )
    }
    res.json(response)
  } catch(error) {
    res.json({ total: 0 })
  }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM