如何失败的Rails的Ajax请求?Rails、Ajax

2023-09-10 16:42:57 作者:人群恐惧症

当用户点击一个特定的项目,我使用 jQuery的POST方法更新的东西在数据库:

When user clicks a specific item, I use jQuery's post method to update something in the database:

$.post("/posts/" + post_id + "/update_something", 
       { some_param: some_value }, 
       success_handler);

其中, update_something 是这样的:

def update_something
  post = Post.find(params[:id])
  post.update_attributes(:some_field => params[:some_param])
  render :nothing => true
end

现在的问题是,如果 update_attributes的失败,请求仍然成功和 success_handler 被执行。

The problem is if update_attributes fails, the request still succeeds and success_handler is executed.

我怎么可能会导致当 update_attributes的失败,使得 success_handler 将不被执行的请求失败?

How could I cause the request to fail when update_attributes fails such that success_handler won't be executed?

推荐答案

您可以做渲染:状态=> 400 (或其他一些错误code)在Rails中,这将触发错误 $回调。AJAX (),也可以使一个错误消息的一些JSON:

You can either do render :status => 400 (or some other error code) in Rails, which will trigger the error callback of $.ajax(), or you can render some JSON with an error message:

渲染:JSON => {:成功=>假}

然后在你的 success_handler 函数,你会:

Then in your success_handler function you would:

function success_handler (response) {
    if (response.success) {
        // do stuff
    }
}

编辑:

哦, update_attributes的失败时返回false。所以,你可以使你的回应基于这一点。

Oh, and update_attributes returns false when it fails. So you can render your response based on that.

编辑2年后:

在几年,看到这有几个upvotes,我会强烈建议使用状态:400 方法,而不是渲染 200 。这是什么错误处理程序的AJAX请求是,应该使用这种方式。

After a couple years and seeing that this has a few upvotes, I'd highly recommend using the status: 400 method instead of rendering 200. It's what the error handler in AJAX requests are for, and should be used that way.