【问题标题】:Console error present even when fail is caught?即使捕获到失败也存在控制台错误?
【发布时间】:2017-07-12 00:38:46
【问题描述】:

我第一次做一些 ajax... 代码:

jQuery

form_ajax_promise = $.ajax({
  type : "POST",
  url :  '/orders/create_or_update',
  dataType: 'json', 
  contentType: 'application/json',
  data : JSON.stringify(params)
})
form_ajax_promise.then(
  function(response) {
    formSuccess(response)
  },
  function(response) {
    formFailure(response) 
  }
)

控制器

def create_or_update
  if @object.save
    # corresponds with formSuccess
    render json: {"id" => @order.id}, status: 200
  else
    # corresponds with formFailure
    render json: {"errors"=> @order.errors.full_messages}, status: 400
  end
end

success 路径运行良好。在测试failure路由时,假设formFailure只是一个简单的函数……

function formFailure(response){
  console.log("successfully inside of formFailure")
}

我注意到正在发生的是console 显示了上述适当的日志消息,但也显示了一个错误:

Failed to load resource: the server responded with a status of 400 (Bad Request)

这个错误应该发生吗?我觉得既然我在$.then 中提供了足够的fail,它不应该吗?

编辑

抱歉,这不是多次渲染/重定向的情况,我只是懒惰并删除了其他代码,因为我只是试图描述失败行为。我的错。代码在上面编辑。

【问题讨论】:

  • 您正在使用status: 400 进行渲染,所以这是正确的行为。
  • 二问(1)jQuery是哪个版本的? (2)form_ajax_promise是否进一步处理?
  • 1) jQuery 2.2.4, 2) 没有进一步处理
  • @Sajan Ok 绝对不知道!我想我的印象是,当代码没有捕获/处理某些事情时会弹出控制台错误,并且我认为我的代码足以处理错误情况。鉴于您告诉我的内容,这是错误的,所以我认为即使在状态为 200 的错误情况下我也会做出回应,并在数据字段中附加一些内容,表明情况并非如此。你觉得这样更合适吗?
  • 使用 jQuery form_ajax_promise 没有进一步处理,但这是唯一有意义的事情;错误处理程序未捕获到错误,然后一些稍后的错误处理程序记录错误。

标签: javascript jquery ruby-on-rails ajax jquery-deferred


【解决方案1】:

也许这样的事情会做。这将在@order 保存成功时返回success,当@order 无效时返回error

def create_or_update
  # Your code here to create or update @order
  if @order.save
    # corresponds with formSuccess
    render json: {"id" => @order.id}, status: 200
  else
    # corresponds with formFailure
    render json: {"errors"=> @order.errors.full_messages}, status: 400
  end
end

【讨论】:

  • 对不起,我只是在缩写代码并且很懒惰,这就是正在发生的事情
【解决方案2】:

通常,这种代码会导致多次渲染或重定向错误。如果不使用条件/分支语句(如 if 或使用 return 语句),则不能在同一函数中使用多个渲染或重定向。

在你的情况下,

render json: {"errors"=> @order.errors.full_messages}, status: 400

已呈现,它指示浏览器收到错误代码 400(这是错误请求),因此您在控制台中看到此错误。 更好地使用上面@Deepak Mahakale 共享的代码。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多