3

在我的布局文件中,我有两个下拉菜单。当在一个(类别)中进行选择时,需要更新第二个(项目)的内容。

在布局文件中:

<div id="pull_down_items" class="pull-right">
    <%= render :partial => 'layouts/pull_down_items' %>
</div>
<%= render :partial => 'layouts/pull_down_category' %>

布局/_pull_down_items.html.erb:

<%= select_tag "current_item", options_from_collection_for_select(current_category.items, "id", "item_name", session[:current_item]), :id=>"change_current_item", :remote => true %>

布局/_pull_down_category.html.erb:

<%= select_tag "current_category", options_from_collection_for_select(categories, "id", "category_name", session[:current_category]), :id=>"change_current_category", :remote => true %>

application.js 中的 jQuery:

$("#change_current_category").change(function() {
  var category_id = $(this).val();
  var url = "/system/" + category_id + "/change_category";
  $.post(url, category_id, function(html) {
  });
});

在我的系统控制器中:

  def change_category
    unless params["id"].blank?
      session[:current_category] = params["id"].to_i
      current_category.reload # this is a method in application_controller.rb
    end
    respond_to do |format|
      format.js
    end
  end

在 change_team.js.erb 中:

$("#pull_down_items").html("<%= render :partial => 'layouts/pull_down_items' %>")

结果: session[:current_category] ​​被更改为正确的类别。项目下拉菜单 div 不会重新加载。

谢谢你的帮助。

4

1 回答 1

1

默认情况下,jQuery.post不保证执行它下载的内容。尝试将dataType参数设置为“脚本”,如http://api.jquery.com/jQuery.post/上所示

“脚本”:将响应评估为 JavaScript,并将其作为纯文本返回。通过将查询字符串参数“_=[TIMESTAMP]”附加到 URL 来禁用缓存,除非缓存选项设置为 true。注意:这会将 POST 转换为远程域请求的 GET。

于 2013-01-09T09:17:46.660 回答