简体   繁体   English

使用jQuery在Rails中使用另一个控制器呈现页面上的部分表单

[英]Render partial form on page with another controller in Rails with jQuery

On my main page I have a search form that is submitting to the search-controller. 在我的主页上,我有一个搜索表单正在提交给搜索控制器。 On the same page I have another form for registering new resources that is submitting to the resources-controller. 在同一页面上,我还有另一种表单,用于注册提交给资源控制器的新资源。 The resource form is rendered as a partial, with the form_for tag inside the partial. 资源表单呈现为局部,其中form_for标记位于局部内。 Everything works fine if the validation is successful, but when it's not, and the form is rerendered with jQuery, the submit button on the resource form no longer submits to the resources-controller, but to the search-controller. 如果验证成功,则一切正常,但是如果验证失败,并且使用jQuery重新呈现表单,则资源表单上的提交按钮不再提交给资源控制器,而是提交给搜索控制器。 Is this because the form_for properties are set when the DOM is loaded when the page is rendered initially? 这是因为在最初呈现页面时加载DOM时设置了form_for属性吗? Is there a way to make this work? 有没有办法使这项工作? Is there something like the .live()-function that can be used in this case? 在这种情况下是否可以使用类似.live()函数的功能?

Here is how the partial is initially rendered in the search/index.html.erb file: 以下是在search / index.html.erb文件中最初呈现部分内容的方式:

<div id="new_resource_form" style="display:block">
  <%= render "resources/resource_form" %>
</div>

This is the form_for part of the resource_form partial: 这是resource_form部分的form_for部分:

<%= form_for @resource, :url => {:controller => 'resources', :id => @resource.id }, :remote => true do |f| %>

The jQuery used to rerender the partial is like this: 用于重新渲染部分的jQuery如下所示:

$('#new_resource_form').html('<%= escape_javascript raw render 'resources/resource_form' %>')

When you click on a submit button the click event bubbles until it reaches the surrounding form and the form submits - the submit button doesn't actually 'point' to anything. 当您单击提交按钮时,单击事件会冒泡,直到到达周围的表单并且表单提交为止-提交按钮实际上并没有“指向”任何内容。 So it sounds as if the problem you are having is that when the form is re-rendered, the html is placing the submit button outside the resource form and inside the search form. 因此,听起来好像您遇到的问题是,当重新呈现表单时,HTML将提交按钮放置在资源表单的外部和搜索表单的内部。 Is there perhaps an error in your template html that the browser is trying to fix? 您的模板html中可能存在浏览器试图修复的错误?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM