Sto avendo un po 'di problemi a far funzionare il jQuery Form Plugin correttamente con un campo di caricamento file. Quando utilizzo il plug-in per inviare il modulo senza un campo di caricamento file, la parte format.json
del blocco respond_to do |format|
viene chiamata correttamente. Tuttavia, aggiungendo il campo caricamento file, esegue solo la parte format.html
che fa sì che il mio codice javascript pensi che si sia verificato un errore.Utilizzo di respond_to ... format.json e jQuery Form Plugin di malsup
Qualcuno si è imbattuto in questo in precedenza o conosce un modo per forzare il plug-in a utilizzare sempre json? In alternativa, posso modificare l'url che il plugin usa per forzare Rails a rendere il json?
Grazie mille per qualsiasi aiuto! Codice seguente:
# app/controllers/details_controller.rb
def create
@detail = Detail.new(params[:detail])
style = params[:detail_style].to_sym || :thumb
data = { :id => '5', :url => 'test.rails' }
respond_to do |format|
if @detail.save
flash[:notice] = 'Your image has been saved.'
data = { :id => @detail.id, :url => @detail.data.url(style) }
format.html { redirect_to :action => 'index' }
format.json { render :json => "<textarea>#{data.to_json}</textarea>", :status => :created }
else
format.html { render :action => 'new' }
format.json { render :json => @detail.errors, :status => :unprocessable_entity }
end
end
end
/* app/views/sidebar/_details.html.erb (excerpt) */
<% form_for(Detail.new, :html => { :multipart => true }) do |f| %>
<%= hidden_field_tag 'detail_style', 'thumb' %>
<%= f.label :image, "Recent Images" %>
<%= f.file_field :image%>
<p>
<%= f.submit "Upload" %>
</p>
<% end %>
<script>
$(document).ready(function() {
var options = {
dataType: 'json',
success: function(json, statusText) {
console.log("success: " + json);
},
error: function(xhr, statusText, errorThrown) {
console.log("error: " + xhr.responseText);
}
};
$('#new_detail').ajaxForm(options);
});
Ho provato a impostare l'intestazione Accept, nel callback beforeSend, ma ciò non ha avuto alcun effetto. Quando ho guardato il codice di jQuery.form, l'oggetto XHR passato a beforeSend ha una funzione vuota inizializzata su "setRequestHeader". Tuttavia sto guardando la versione 2.16 del file, forse ci sono cambiamenti nelle versioni successive. – Prashant