Iam在Rails中构建表单.我想通过ajax提交,因此我将remote设置为true
<%= form_for @post, html: { multipart: true }, remote: true do |f| %>
...
<%= end %>
在我的控制器中:
def create
@post = Post.new(post_param)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render json: @post.errors, status: 400 }
format.json { render json: @post.errors, status: 400 }
end
end
end
以表格形式显示
$('#new_post').on('ajax:success', function(data) {
console.log(data);
}).on('ajax:error', function(evt, xhr, status, error) {
console.log(xhr);
});
但是在’ajax:error’事件中,我无法解析以获取有关发布验证错误的数据.所有参数“ xhr”,“状态”,“错误”都等于未定义.
如何解析“ ajax:error”中的响应以获取有关验证错误的数据?
解决方法:
Rails 5.1引入了rails-ujs,它更改了这些事件处理程序的参数.以下应该工作:
// ...
.on('ajax:error', function(event) {
var detail = event.detail;
var data = detail[0], status = detail[1], xhr = detail[2];
// ...
});
来源:http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。