即使发生故障,控制台也会出现错误?

时间:2017-02-22 05:32:33

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

我第一次做了一些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)

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

修改

对于混淆的道歉,这不是多重渲染/重定向的情况,我只是懒惰并且删除了其他代码,因为我只是试图描述失败行为。我的错。代码编辑如上。

2 个答案:

答案 0 :(得分:1)

也许这样的事情会发生。成功保存success时会返回@ordererror无效时会@order

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

答案 1 :(得分:0)

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

在你的情况下,

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

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

希望这有帮助