javascript - 如何使用 json 数组填充 Rails 下拉菜单

标签 javascript ruby-on-rails json jquery

我有一个 Ant 展示页面,显示各种 Ant 的详细信息。该页面上有两个下拉菜单,一个用于环境:[室内、室外],另一个用于饮食:[糖、脂肪、蛋白质]。

当您从每个参数中选择一个参数时,它会根据参数呈现出一个产品页面。但是,有些组合会导致 nil,例如木匠 Ant 没有与室内糖相关的产品。

我正在尝试根据组合是否为零来填充下拉菜单。如果有人选择室内,如果该组合不存在,我希望糖不要出现在下一个下拉列表中。

到目前为止,我有两种方法只为可用项目创建 json 数组:

def food_sources
  food_sources = Ant.find(params[:ant_id]).product_recommendations.where(environment: params[:environment]).map(&:diet)
  render json: food_sources.to_json
end

def environments
  environments = Ant.find(params[:ant_id]).product_recommendations.where(diet: params[:diet]).map(&:environment)
  render json: environments.to_json
end

例如,如果输入

http://localhost:3000/ants/27/food_sources?environment=indoor

它返回到浏览器中

["sugar","protein"]

对于 id 为 27 的 Ant ,bc 只有两种户外室内饮食选择,而不是可能的三种。

我的问题是,如果有人选择了上述组合,我该如何将这个数组传递到我的 Rails 下拉列表中?

编辑

= form_tag ant_product_recommendations_path(@ant.id), id: 'select_box',  method: :get do |form|
  %h3 What food source are they currently feeding on?
  = select_tag :environment, options_for_select([["Select One"], "Indoor", "Outdoor"])
  %h3 
    Locate the nest by following the ants back from their food source.
    %br
    Where is the nest located?
  = select_tag :diet, options_for_select([["Select One"], "Sugar", "Fat", "Protein"])
  = submit_tag "Find Solutions", class: 'submit button' 
  = link_to 'Go Back', '/', class: 'go_back'

最佳答案

在我看来,您想动态填充下拉框,这将有助于 ajax 调用,如下所示:

$('#select_box').on('change', function () {
    $.ajax({
        url: "/controller/action",
        type: 'get',
        data: $(this).serialize()
    }).done(function (data) {
        change_select(data);
    });
});

function change_select(data) {
    var json = jQuery.parseJSON(data);
    var options = [];
    json.each(function (key, index) {
        options.push({text: index, value: key});
    });
    $("#select_box").replaceOptions(options);
};

这将允许您指定下拉列表的选项,并且您可以这样使用 Controller :

  @food_sources = Ant.find(params[:ant_id]).product_recommendations.where(environment: params[:environment]).map(&:diet)
  respond_to do |format|
    format.json { render json: @food_sources }
  end

关于javascript - 如何使用 json 数组填充 Rails 下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19392553/

相关文章:

ruby-on-rails - 如何安全地检索可能不存在的 Ruby 方法的值?

javascript - 为什么这段代码在 AngularJS 1.2 中不起作用?

javascript - 如何使用调用函数的按钮移动 Canvas 中的文本以使文本显示在 Javascript 中?

javascript - data.buffer.length 返回未定义

json - firebase 数组解析 json 总是失败

android - Retrofit 2,解析json,忽略数组内部的错误数据类型

java - 写入文件时如何考虑JSON结构

javascript - 是否有一种设计模式的功能类似于观察者与装饰者的混合?

ruby-on-rails - Rails sprockets 不预编译 Assets

ruby-on-rails - 在销毁 rails 之前检查所有关联