【问题标题】:Rails 3.1 Submit form without refreshRails 3.1提交表单而不刷新
【发布时间】:2012-04-10 16:54:30
【问题描述】:

我的orders/_form.html.erb 上有一个表格,我想提交并保存在一个名为“类别”的表格中

<%= simple_form_for(@category) do |f| %>

  <%= f.error_notification %>

  <div class="inputs">

    <%= f.input :name, 

:label => false, 

:input_html => { :class => 'text', 

:style => 'float:left; width:250px' }, 

:placeholder => "Type of item / name of expense",


%>



   <%= f.hidden_field :user_id, 

:value => current_user.id %>


   <%= f.button :submit, 

:value => 'Add Category', 

:class => 'small grey',

:style => 'margin:5px 0 0 10px' %>


  </div>



<% end %>

在我的 categories_controller.rb 我有这个代码来创建类别:

# POST /categories

  # POST /categories.json

  def create

    @category = current_user.categories.build(params[:category])



    respond_to do |format|

      if @category.save

        format.html { redirect_to new_order_path }

        format.json { render json: new_order_path, status: :created, location: @category }

      else

        format.html { render action: "new" }

        format.json { render json: @category.errors, status: :unprocessable_entity }

      end

    end

  end

首先,我怎样才能使提交表单时不刷新页面?然后我希望类别下拉列表http://d.pr/gUwz 也有新条目(我假设使用 JQ)。知道如何让我开始这样做吗?

【问题讨论】:

    标签: jquery ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    在 Rails 3.x 中,您必须在表单中使用 :remote =&gt; true

    例如:

    <%= form_for @comment, :remote => true, :html => { :'data-type' => 'html', :id => 
     <form code>
    <% end %>
    

    并确保包含 jQuery js 文件。

    【讨论】:

    • 好的,所以我把它放在simple_form中......提交后新内容如何出现在该页面上?
    • 还有,表单提交后,如何做到不让人们点击一百万次?
    【解决方案2】:

    你应该使用表单标签发送一个 ajax 请求:

    :远程 => 真

    查看有关 for_for 方法的文档:FormHelper#form_for-instance_method

    由于 JQuery 默认使用 rails 3.0,你应该没有问题。

    【讨论】:

      【解决方案3】:

      需要在表单标签中使用 :remote => true,这将提交表单与 ajax 请求一样,并且表单将在不刷新页面的情况下提交。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-20
        • 2015-10-10
        • 1970-01-01
        相关资源
        最近更新 更多