【发布时间】:2010-02-09 14:53:03
【问题描述】:
让jQuery Form Plugin 与文件上传字段一起正常工作有点麻烦。当我使用插件提交没有文件上传字段的表单时,respond_to do |format| 块的format.json 部分被正确调用。但是,通过添加文件上传字段,它只执行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);
});
【问题讨论】:
标签: ruby-on-rails json file-upload jquery-forms-plugin