【问题标题】:unable to handle HTTP 422 with best in place rails无法使用最佳轨道处理 HTTP 422
【发布时间】:2015-03-14 14:11:21
【问题描述】:

我的控制器代码是这样的:

def update
respond_to do |format|
  if refresh_quantity_in_inventory
    format.json { render json: { message: "Quantity successfully updated" } }
  else
    format.json { render json: @errors, status: :unprocessable_entity }
  end
end

结束

CoffeeScript 是这样的:

ready = ->
   $('#best_in_place_cart_quantity').best_in_place().bind 'ajax:error', (evt, data, status, xhr) ->
      alert xhr
      alert xhr.status
      if (xhr.status == 422)
        alert("Inventory count is not enough")
$(document).ready ready
$(document).on "page:load", ready

我也试过ajax:success,但都没有触发回调。我如何捕捉 422?我该怎么办?


$('#best_in_place_cart_quantity').best_in_place().done((data, status, response) ->
    alert 'Done handler. HTTP code: ' + response.status
    return
  ).fail (error) ->
    alert 'Fail handler. HTTP code: ' + error.status
    return

这也不起作用。

【问题讨论】:

    标签: jquery ruby-on-rails coffeescript best-in-place


    【解决方案1】:

    这是最终起作用的代码。

    $('.best_in_place_cart_quantity').best_in_place()
    
    $(".best_in_place_cart_quantity").bind 'ajax:error',  (evt,  data,  status,  xhr) ->
        alert "Not enough quantity"
    

    经验教训是,我们应该通过类而不是 Id 将最佳字段绑定在适当的位置。

    【讨论】:

      【解决方案2】:

      此代码示例展示了如何使用 JQuery(即 422)处理 HTTP 错误:

      $.get('http://httpbin.org/status/422')
          .done(function(data, status, response) {
              alert('Done handler. HTTP code: ' + response.status);
          })
          .fail(function(error) {
              alert('Fail handler. HTTP code: ' + error.status);
          });  
      

      Here 是这段代码的 sn-p。

      尝试采用上述代码并将ready处理程序替换为:

      $ ->
         // your code here
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 2021-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多