我发现类似的StackOverflow问题这里和这里 ,但仍不能得到这个工作。
我使用Rails 3.2.8,2.0.4 SimpleForm和Twitter的引导2.1.1(通过引导,萨斯宝石2.1.1.0)。
用户应该能够添加从模式弹出窗口中的联系人。 如果有验证错误,他们应该内嵌显示,就像用户使用形式的非模态版本(红色边框领域,错误信息字段旁边)。
我加载像这样的模式:
<a data-toggle="modal" data-target="#new-contact-modal">Go modal!</a>
这里是自举模式,它调用相同的contacts/contact_fields
在非模式版本局部使用。 应用程序/视图/联系人/ _new_modal.html.erb:
<div id="new-contact-modal" class="modal hide fade" tabindex="-1"
role="dialog" aria-labelledby="new-contact-modal-label"
aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h3 id="new-contact-modal-label"><%= t("contacts.new.header") %></h3>
</div>
<%= simple_form_for(@contact,
:remote => true,
:html => {:class => "form-horizontal",
"data-type" => :json }) do |contact_form| %>
<div id="new-contact-body" class="modal-body">
<%= render 'contacts/contact_fields', :f => contact_form %>
</div>
<div class="modal-footer">
<%= contact_form.submit :class => "btn btn-primary",
:"data-loading-text"=> ('simple_form.creating') %>
<%= t('simple_form.buttons.or') %>
<a data-dismiss="modal" aria-hidden="true">
<%= t('simple_form.buttons.cancel') %>
</a>
</div>
<% end %>
</div>
应用程序/控制器/ contacts_controller.rb(故意注释掉format.json
行,因为我想送回去使用JavaScript全模式):
def create
@contact = Contact.new(params[:contact])
<...some additional processing...>
respond_to do |format|
if @contact.save
format.html { flash[:success] = "Contact added."
redirect_to @contact }
format.json { render json: @contact, status: :created, location: @contact}
else
format.html { render action: "new" }
#format.json { render json: @contact.errors, status: :unprocessable_entity }
format.js { render 'new_modal_error' }
end
应用程序/视图/联系人/ new_modal_error.js.erb
var modal = "<%= escape_javascript(render :partial => 'contacts/new_modal', :locals => { :contact => @contact.errors }) %>";
$("#new-contact-modal").html($(modal));
应用程序/资产/ Java脚本/ contacts.js一些jQuery来重置表单,并关闭在成功的模式。
$(function($) {
$("#new_contact")
.bind("ajax:success", function(event, data, status, xhr) {
// http://simple.procoding.net/2008/11/22/how-to-reset-form-with-jquery :
$(this).each(function(){
this.reset();
});
$("#new-contact-modal").modal("hide");
})
});
好消息是,这个工程当表单没有错误:添加联系人和模态是隐藏的。 但是,如果有验证错误,我得到的消息“JSON.parse:意外的字符”。 这个来自的jquery.js,线515,这是return
在这个片段中的语句:
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
如果我检查data
,我看到的是我的内容new_modal_error.js
文件,与形状误差完全展开,并且逃脱了对JavaScript。 但它不是JSON。
我在想什么? 如何让页面处理new_modal_error.js
作为一个JavaScript文件,而不是一个JSON变量? 或者是有干脆处理这个更简单的方法?