从发布请求中捕获AJAX错误(422)

时间:2019-07-13 15:34:42

标签: ajax shopify

我有以下Ajax,但是它需要处理返回的422错误(这意味着缺货)。我已经尝试了几种方法,但是出现了错误,并且拒绝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();

1 个答案:

答案 0 :(得分:1)

  

我已经尝试了几种方法,但是出现了错误,并且拒绝POST。

我了解的是,您在浏览器控制台中看到此错误。这是无法避免的,但这并不意味着您的请求没有通过。 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();

AJAX Error Docs