【发布时间】:2016-02-15 04:50:45
【问题描述】:
我有一个表格(#new_group),写成:
<%= form_for @group, remote: true, html: {role: :form, 'data-model' => 'group', class: 'form-horizontal', id: "new_group"} do |f| %>
我将所有 ajax 调用设置为 :json 数据类型
//Default to JSON responses for remote calls
$.ajaxSetup({
dataType: 'json',
cache: false
})
提交表单,正确处理为:son
def create
@group = Group.new(group_params)
respond_to do |format|
if @group.save
format.html { ... }
format.json { ... }
else
format.html { ... }
format.json {
errors = {errors: @group.errors.full_messages}
byebug
render(json: errors.to_json, status: :unprocessable_entity )
}
end
end
debugging :
(byebug) errors.inspect
{:errors=>["Group already defined"]}
但是我可以在控制台中阅读:
POST http://localhost:3000/groups 422 (Unprocessable Entity)
XHR finished loading: POST "http://localhost:3000/groups"
为什么 422 http 错误没有被捕获为 ajax:error 事件? 我写道:
$("#new_group")
.on("ajax:success", function(e, data, status, xhr) {
console.log("new group added!");
})
.on("ajax:error", function(e, data, status, xhr) {
console.log("ERROR: " + status);
errors = xhr.responseJSON.error;
});
【问题讨论】:
标签: ajax ruby-on-rails-4 http-error