javascript – 如何使用json数组填充Rails下拉菜单
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 如何使用json数组填充Rails下拉菜单,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2173字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 如何使用json数组填充Rails下拉菜单](/upload/InfoBanner/zyjiaocheng/744/10eb6e9a264748aeb6385da6609c46c4.jpg)
我有一个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"]
bc对于id为27的蚂蚁,只有两种户外室内饮食选择,而不是可能的三种.
我的问题是,如果有人选择了上述组合,我如何将此数组传递到我的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);
};
这将允许您指定下拉列表的选项,您可以通过以下方式使用控制器:
@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下拉菜单全部内容,希望文章能够帮你解决javascript – 如何使用json数组填充Rails下拉菜单所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。