使用AJAX(Ruby on Rails)获取提交的值

时间:2014-07-07 14:29:03

标签: jquery ruby-on-rails ajax

我在视图中有这段代码

<form>
<%= form_tag(portefeuillemodele_path, :remote => true) do %>
  <%= label_tag(:date, "The selected date is:") %>
  <%= text_field_tag(:date) %>

  <%= submit_tag("OK") %>
<% end %>
</form>

这在我的控制器中

  def index
    @portefeuillemodeles = Portefeuillemodele.all
    @date = params[:date]

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @portefeuillemodeles }
    end
  end

当我按下提交按钮时,它没有做任何事情。 我安装了ajax gem,我需要保存提交的值,所以我可以在我的视图中使用它?

1 个答案:

答案 0 :(得分:1)

查看您的代码

<form> // you don't need this tag form_tag will create those tags for you
  <%= form_tag(portefeuillemodele_path, :remote => true) do %>
    <%= label_tag(:date, "The selected date is:") %>
    <%= text_field_tag(:date) %>

    <%= submit_tag %>
  <% end %>
</form>

其次,当你使用ajax时,你的控制器需要js格式

def index
  @portefeuillemodeles = Portefeuillemodele.all
  @date = params[:date] # this will give you access to your date but you need to check your params to be sure

  respond_to do |format|
    format.html # index.html.erb
    format.js{} # ajax will call this format not html or json
    format.json { render json: @portefeuillemodeles }
  end
end

这将允许rails查找名为 index.js.erb 的文件,您可以通过js 操作DOM元素。有关详细信息,请参阅Working with Javascript in Rails

相关问题