Sto costruendo un modulo in Rails. Voglio inviarlo tramite Ajax, quindi ho deciso remote: true
<%= form_for @post, html: { multipart: true }, remote: true do |f| %>
...
<%= end %>
Nel mio 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
In forma a vista
$("#new_post").on("ajax:success", function(data) {
console.log(data);
}).on("ajax:error", function(evt, xhr, status, error) {
console.log(xhr);
});
Ma in caso di "ajax: errore", non riesco ad analizzare i dati sugli errori di convalida di post. Tutti i parametri "xhr", "status", "error" sono entrambi non definiti.
Come analizzare la risposta in "ajax: errore" per ottenere dati sugli errori di convalida?
risposte:
1 per risposta № 1Introduzione di Rails 5.1 rails-ujs
, che modifica i parametri di questi gestori di eventi. Il seguente dovrebbe funzionare:
// ...
.on("ajax:error", function(event) {
var detail = event.detail;
var data = detail[0], status = detail[1], xhr = detail[2];
// ...
});
Fonte: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers