ajax - 从发布请求中捕获 AJAX 错误 (422)
问题描述
我有以下 Ajax,但它需要处理422
返回的错误(这意味着Out of Stock)。我已经尝试了几种方法,但它出错并且拒绝POST
说明:
Failed to load resource: the server responded with a status of 422 ()
我不确定如何捕捉422
错误并向用户返回显示缺货的内容。
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
解决方案
我已经尝试了几种方法,但它出错并拒绝发布。
我所了解的是,您在浏览器控制台中看到此错误。它无法阻止,但这并不意味着您的请求没有通过。Shopify 收到 POST 请求并发送状态为 422 的响应,因此这被视为错误(非 2xx 响应代码被视为错误)。
要处理错误并显示错误消息,请相应地调整代码。检查更新的代码和代码注释。
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
推荐阅读
- datatable - 需要帮助选择过滤数据表 1.10 的性别,以匹配准确的男性和女性关键字
- python - 输入类型不支持 seaborn heatmap ufunc 'isnan'
- python - 3D nrrd 图像可视化(matplotlib)?
- aws-lambda - 在 AWS Lamba 上创建实体类
- c# - 不同函数的不同数组值
- c# - Windows 生物识别框架:AcquireFocus() 无法正常工作。错误访问被拒绝:0x80070005
- python - GstBus 没有收到 EOS 事件
- node.js - 为什么heroku在部署时找不到我的节点模块?
- android - 共享元素活动转换具有奇怪的性能
- python - 循环通过genfromtxt对象获取子字符串并放入sqlite数据库