使用 Ruby on Rails 4 和 Ruby 2。
这是我的简单控制器操作。当验证失败时,我会渲染“新”动作并将视图的内容注入到.ajax-target
div 中。
$("body").on("ajax:success", '.remote-form', (e, data, status, xhr) ->
$(this).parent().parent().after(xhr.responseText);
$.colorbox.resize();
).on "ajax:error", '.remote-form', (e, xhr, status, error) ->
$(this).parent().parent().after("Error");
def create
@floor = Floor.new(floor_params)
if @floor.save
render action: 'edit', layout: false
else
render action: 'new', layout: false
end
end
#popupBox.ajax-target
%h1 New Floor
= render 'shared/form_errors', resource: @floor
#formHolder
= simple_form_for @floor, html: { multipart: true, class: 'remote-form' }, remote: true do |f|
= f.input :name, required: true
= f.input :prefix, required: true
= f.input :plan, class: 'file_hidden', label: 'Floorplan'
.clearfix
= f.button :submit, 'Create Floor'
这种工作结构适用于每种类型的表单,除了具有文件输入类型且具有选定文件的表单。如果我提交所有字段为空白的表单,我会看到表单重新加载正常。如果我选择一个图像并将其他字段留空(以触发验证),我会得到:
“错误”文本,因为ajax:error
响应。还可以在“网络”选项卡中查看:
<textarea data-type="text/html" data-status="200" data-statusText="OK"><div class='ajax-target' id='popupBox'>
<h1>New Floor</h1>
<div id='popupErrors'>
<ul>
<li>
<strong>Prefix</strong>
has already been taken
</li>
</ul>
</div>
<div class='clearfix'></div>
<div id='formHolder'>
<form accept-charset="UTF-8" action="/floors" class="simple_form remote-form" data-remote="true" enctype="multipart/form-data" id="new_floor" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /></div> <div class="input string required floor_name"><label class="string required control-label" for="floor_name"><abbr title="required">*</abbr> Name</label><input class="string required" id="floor_name" name="floor[name]" type="text" value="FLR001" /></div>
<div class="input string required floor_prefix field_with_errors"><label class="string required control-label" for="floor_prefix"><abbr title="required">*</abbr> Prefix</label><input class="string required" id="floor_prefix" name="floor[prefix]" type="text" value="FLR001" /></div>
<div class='clearfix'></div>
<div class="input file required floor_plan"><label class="file required control-label" for="floor_plan"><abbr title="required">*</abbr> Floorplan</label><input class="file required" id="floor_plan" name="floor[plan]" type="file" /></div>
<div class='clearfix'></div>
<input class="btn" name="commit" type="submit" value="Create Floor" />
</form>
</div>
</div>
</textarea>