从post请求捕获AJAX错误(422)

从post请求捕获AJAX错误(422),ajax,shopify,Ajax,Shopify,我有以下Ajax,但它需要处理返回的422错误(这意味着缺货)。我试过几种方法,但都是错误的,拒绝发表声明: 加载资源失败:服务器响应状态为422() 我不确定如何捕捉422错误,并将显示缺货的内容返回给用户 Shopify.moveAlong = function() { // If we still have requests in the queue, let's process the next one. if (Shopify.queue.l

我有以下Ajax,但它需要处理返回的
422
错误(这意味着缺货)。我试过几种方法,但都是错误的,拒绝发表声明:

加载资源失败:服务器响应状态为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();