[英]Javascript - cart only adds 1 item one even if 2 or 5 the item are buyed
[英]Ajax is not responding when my cart contains only one item
在我的購物車頁面中,當用戶選擇的產品數量小於一個時,我試圖刪除一個產品。 這種變化也應該反映在產品總量上。 我為此目的使用 ajax ,它僅在購物車包含多個項目而不是單個項目的情況下刪除產品。
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)
})
})
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 })
})
}
})
}
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
}
}
})
}
在此圖像中,您可以看到用戶的購物車中有多個產品。 當用戶更改第二個產品數量時,'qtyChange' object 變為真,而當數量達到零時他/她點擊(-)按鈕'removeProduct'變為真。 我已經在這張圖片的右側標記了這些更改。
在這張圖片中,您可以看到我試圖將數量從 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.