我可能遗漏了一些东西,这是我的问题。
我有一个提交图像的表单,我希望表单使用 AJAX,但在提交时它响应 HTML 格式而不是 JS。为什么POST请求不使用JS格式??我还使用carrierwave上传文件。
在我的控制器中mission_slides_controller.rb
def new
@account = Account.find(params[:account_id])
@mission = Mission.find(params[:mission_id])
@mission_slides = MissionSlide.where('mission_id = ?', @mission.id)
slides = MissionSlide.where('mission_id = ?', @mission.id)
@mission_slide = MissionSlide.new
if slides.size < 1
@mission_slide.position = 1
else
@mission_slide.position = slides.last.position+1
end
respond_to do |format|
format.html # new.html.erb
format.js
format.json { render json: @mission_slide }
end
end
def create
@mission_slide = MissionSlide.new(params[:mission_slide])
@account = Account.find(params[:account_id])
@mission = Mission.find(params[:mission_id])
respond_to do |format|
if @mission_slide.save
format.html { redirect_to user_account_path(current_user, @account), notice: 'Mission slide was successfully created.' }
format.json { render json: @mission_slide, status: :created, location: @mission_slide }
format.js
else
format.html { render action: "new" }
format.json { render json: @mission_slide.errors, status: :unprocessable_entity }
format.js
end
end
end
在我的控制器中_form.html.erb
<div class="slides">
<h4>Current slides</h4>
<%= render 'mission_slides' %>
</div>
<%= form_for([current_user, @account, @mission, @mission_slide], :remote => true, :multipart => true) do |f| %>
<%= render :partial => "layouts/form_messages", :locals => {:model_name => @mission_slide, :heading => t('errors.template.header', :count => @mission_slide.errors.size, :model => @mission_slide.class) } %>
<%= f.hidden_field :mission_id, :value => @mission.id %>
<div class="form-group required mission_slide_name">
<div>
<%= f.label :name, :class => "control-label required-label" %>
<div>
<%= f.text_field :name, :class => "form-control", :placeholder => "Slide Name" %>
</div>
</div>
</div>
<div class="form-group required mission_slide_image">
<div>
<%= f.label :image, :class => "control-label required-label" %>
<div>
<%= f.file_field :image, :class => "form-control" %>
</div>
</div>
</div>
<div class="form-group required mission_slide_position">
<div>
<%= f.label :position, :class => "control-label required-label" %>
<div>
<%= f.number_field :position, :class => "form-control" %>
</div>
</div>
</div>
<div class="form-group">
<div>
<%= f.submit "Add slide", :class => "btn btn-blue" %>
</div>
</div>
<% end %>
我还为 CREATE 操作创建了一个 JS 部分create.js.erb
var container = $("#current_slides")
<% if @mission_slide.errors.present? %>
$("#new_mission_slide").prepend("<%= escape_javascript render :partial => "layouts/form_messages", :locals => {:model_name => @mission_slide, :heading => t('errors.template.header', :count => @mission_slide.errors.size, :model => @mission_slide.class) } %>");
<% else %>
$('form[id*="new_mission_slide"]').replaceWith('<%= escape_javascript render("form") %>')
$container.append(@mission_slide)
<% end %>
感谢您的明智见解