![](/img/trans.png)
[英]How do I assign my get response data to an array in the order I sent the request
[英]How do I rewrite my AJAX that I will get a response in a particular order?
我正在电子商务网站上制作购物车。
如果用户单击按钮,此脚本将删除一件产品
$(".minusCart").click(function () {
var id = $(this).attr("data-id");
$.post("/cart/deleteOneAjax/" + id, {}, function (data) {
if (!data) {
location.reload();
} else {
$("#id-count" + id).val(data);
}
});
$.post("/cart/countAjax/" + id, {}, function (data) {
$("#cart-count").html(data);
});
$.post("/cart/productPriceAjax/" + id, {}, function (data) {
$("#product-price-cart" + id).html(data);
});
$.post("/cart/totalPriceAjax/" + id, {}, function (data) {
$(".total-price-cart").html(data);
});
});
所以这个脚本应该做的步骤是:
所以顺序真的很重要。 但是因为那些是异步请求,响应可以以不同的顺序发回。 因此,有时我会收到对 /cart/deleteOneAjax/ 的响应,最后一个和所有其他数据计算不正确。
我该怎么做才能解决它?
使用 ajax 而不是使用此 post 方法将使您的请求处理更加可定制。
作为此问题的解决方案,您可以在发布 function 调用之前使用“等待”关键字,然后您必须使点击事件 function 为“异步”。
现在简单的解决方案是使此调用同步,将“post”方法替换为“ajax”调用。
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false //Here I am making it synchronus
});
在这里查看官方文档: https://api.jquery.com/jquery.ajax/
ajax
是异步的 function ,这意味着如果中间有异步 function ,那么 JS 没有必要根据您期望的顺序从第 1 行到第 100 行处理您的代码。
在你的情况下,JS 确实以正确的顺序处理你所有的 ajax 请求,只是它不等待cart/deleteOneAjax
响应然后只处理下一个 ajax cart/countAjax
,等等。
怎么解决?
老办法: Promise 然后
新方式:异步等待
在这里我演示了Promise Then
方式:
function deleteOne(id) {
return new Promise((resolve, reject) => {
$.post("/cart/deleteOneAjax/" + id, {}, function (data) {
if (!data) {
reject("no data")
} else {
resolve(data)
}
});
})
}
function count(id) {
return new Promise((resolve, reject) => {
$.post("/cart/countAjax/" + id, {}, function (data) {
if (!data) {
reject("no data")
} else {
resolve(data)
}
});
})
}
function productPrice(id) {
return new Promise((resolve, reject) => {
$.post("/cart/productPriceAjax/" + id, {}, function (data) {
if (!data) {
reject("no data")
} else {
resolve(data)
}
});
})
}
function totalPrice(id) {
return new Promise((resolve, reject) => {
$.post("/cart/totalPriceAjax/" + id, {}, function (data) {
if (!data) {
reject("no data")
} else {
resolve(data)
}
});
})
}
$(".minusCart").click(function () {
var id = $(this).attr("data-id");
deleteOne(id).then(deleted => {
// your logic before process next ajax
count(id).then(countData => {
// your logic before process next ajax
productPrice(id).then(productPriceData => {
// your logic before process next ajax
totalPrice(id).then(totalPriceData => {
})
})
})
}).catch(deleteError=>{
//logic for deleteOne rejection scenario
})
})
Promise Then
的一个缺点是回调地狱,但那是为了你以后的研究。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.