我有一个表格(#new_group)写成:
<%= form_for @group, remote: true, html: {role: :form, 'data-model' => 'group', class: 'form-horizontal', id: "new_group"} do |f| %>
我将所有ajax调用设置为:json datatype
//Default to JSON responses for remote calls
$.ajaxSetup({
dataType: 'json',
cache: false
})
提交表格,正确处理为:儿子
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;
});
答案 0 :(得分:0)
Rails 4 w turbolinks,我必须写:
$(document).on('ajax:success', '#new_group', function(e, data, status, xhr) {
console.log("data: "+JSON.stringify(data, null, 2));
});
$(document).on('ajax:error', '#new_group', function(e, data, status, xhr) {
//console.log("data: "+JSON.stringify(data, null, 2));
errors = data.responseJSON.errors;
$.each( errors, function( key, message ) {
$("#modalGroupAlert ul").append( '<li>' + message + '</li>' );
});
$( "#modalGroupAlert" ).show();
});