我有一點麻煩讓jQuery Form Plugin與文件上傳領域正常工作。當我使用該插件提交沒有文件上傳字段的表單時,respond_to do |format|
塊的format.json
部分被正確調用。但是,通過添加文件上傳字段,它只執行format.html
部分,這使得我的JavaScript代碼認爲發生了錯誤。使用respond_to ... format.json和jQuery表單插件由malsup
有沒有人遇到過這種情況,或知道強制插件總是使用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);
});
我嘗試在beforeSend回調中設置Accept標頭,但這沒有效果。 當我看着jQuery.form的代碼時,傳遞給beforeSend的XHR對象有一個初始化爲「setRequestHeader」的空函數。不過,我正在查看該文件的2.16版本,也許在以後的版本中有變化。 – Prashant 2010-05-30 09:16:18