我正在用 Rails 构建一个表单。我想通过ajax提交,所以我设置了remote: true
<%= form_for @post, html: { multipart: true }, remote: true do |f| %>
...
<%= end %>
在我的 Controller 中:
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
在 View 中的形式
$('#new_post').on('ajax:success', function(data) {
console.log(data);
}).on('ajax:error', function(evt, xhr, status, error) {
console.log(xhr);
});
但在“ajax:error”事件中,我无法解析以获取有关帖子验证错误的数据。所有参数 'xhr'、'status'、'error' 都等于未定义。
如何解析 '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
关于javascript - 如何从事件 ajax :error in Rails 5. 1 的响应中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43827441/