首页 > 解决方案 > 从发布请求中捕获 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();

标签: ajaxshopify

解决方案


我已经尝试了几种方法,但它出错并拒绝发布。

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


推荐阅读