我在让jQuery 表单插件与文件上传字段正常工作时遇到了一点麻烦。当我使用插件提交没有文件上传字段的表单时,块的format.json
部分respond_to do |format|
被正确调用。但是,通过添加文件上传字段,它只执行format.html
使我的 javascript 代码认为发生错误的部分。
有没有人遇到过这种情况或知道强制插件始终使用 json 的方法?或者,我可以修改插件用来强制 Rails 呈现 json 的 url 吗?
非常感谢您的帮助!下面的代码:
# 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);
});