当用户点击一个特定的项目,我使用 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.
上一篇:要解决这个问题,发送使用AJAX阿拉伯语字符阿拉伯语、解决这个问题、字符、AJAX
下一篇:preserving浏览器"返回]使用AJAX / jQuery的加载页面和history.pushState方法按钮功能()按钮、加载、浏览器、页面