表单提交后呈现表单

我正在尝试在提交上一个表单后呈现表单。 例如,假设我有一个只有选择下拉菜单的表单。 您可以选择其中一个选项,单击“继续”(提交按钮),然后在页面重新加载后,它会根据所选类别呈现新表单。

仅供参考,我正在尝试在Rails应用程序中执行此操作。

这是一个例子: http : //popcornindiana.com/contact-us

您提供的示例是逐页示例。 如果您希望这样做,那么您的表单应该提交到另一个页面,然后将下一个表单作为单独的文档提交。 请注意,当您提交一个表单时,URL会发生变化。 它完全是一个不同的页面。

现在,如果您正在寻找单页表单(您点击提交并且页面不刷新,而是表单刷新),那么您希望使用异步表单提交 。 有很多方法可以做到这一点,包括使用jQuery或者像AngularJS这样的大型框架。

这两种可能的方法,根据您的要求选择,取决于您。

我会查找任何一种方法的教程; 这个问题的性质表明你可能对此缺乏经验,所以我会说有关如何提交表格的教程,然后决定在那之后走哪条路。

为其参数中的每个选择项写下特定的URL。 并在控制器中使用redirect_to params [:url]。

这实际上比我想象的更容易。 我想我更困惑,因为我在用Rails术语思考而不是goo’old HTML。 无论如何,我将分享完整的解决方案:

  1. 为视图创建路由,例如:

    config/routes.rb # this one is the hub, where you choose the contact form you need get 'contact' => 'contacts#contact_page' # this is the 'new' action, where the contact will be created get '/contacts/love-us' => 'contacts#love_us' 
  2. 创建控制器操作:

     app/controllers/contacts_controller.rb class ContactsController < ApplicationController before_action :send_email, except: [:create] def create @contact = Contact.new(params[:contact]) @contact.request = request if @contact.deliver @thank = "Thank you!" @message = "We received your inquiry." else @error = "Cannot send message" end end # to the select where you choose the contact form def contact_page end # to the actual contact form def love_us @the_subject = "Tell us you love us" end # def ... other actions to other contact forms private def send_email @contact = Contact.new end end 
  3. 在此示例中为每个表单创建一个视图:

     app/views/contacts/love-us.html.haml .contact-page %h3 Tell Us You Love Us = form_for @contact do |f| .hide = f.text_field :nickname, hint: 'Leave this empty!' = f.hidden_field :mail_subject, value: @the_subject = f.label :name = f.text_field :name = f.label :message = f.text_area :message = f.submit "Send Message" 
  4. 创建“contact_page”视图以选择所需的联系表单

     app/views/contact/contact_page.html.haml .contact-form %h5 Select a Subject: %form{class: "emailform", name: "emailform"} %select{name: "location", class: "store-select"} %option{selected: "selected", :value => "/contact"} = "---" %option{value: "/contacts/where-to-buy"} WHERE TO BUY %option{value: "/contacts/nutritional-ingredients"} NUTRITIONAL AND / OR INGREDIENTS %option{value: "/contacts/order-status"} ORDER STATUS AND TRACKING %option{value: "/contacts/product-complaint"} SPECIFIC PRODUCT COMPLAINT %option{value: "/contacts/company-related"} COMPANY RELATED OR OTHER %option{value: "/contacts/love-us"} TELL US YOU LOVE US %input{name: "submit", type: "button", value: "Continue", onclick: "self.location=document.emailform.location.value"}/