Rails-通过选择下拉菜单执行Ajax调用 [英] Rails - execute an ajax call via select dropdown menu
问题描述
我有一个包含select
标记的视图,它不是表单的一部分,而只是一个独立的下拉菜单.单击其中一个选项后,我要执行一个ajax调用
I have a view that contains a select
tag, it is not part of a form just a stand alone drop down menu. On clicking one of the options I want to execute an ajax call
这是选择标签
<%= select_tag 'application_stage', options_for_select(application.job.hiring_procedure.hiring_procedure_stages.map{ |p| [p.name, p.id] }), prompt: "Hiring stage", class: 'input-block-level chzn-select hiring_stage_dropdown', id: 'hiring_stage_dropdown' %>
这是一个基本的jquery,我试图通过它来检测更改
and this is a basic jquery through which I am trying to detect the change
jQuery(function($) {
console.log('clicked');
$("#hiring_stage_dropdown").click(function() {
var state = $('select#hiring_stage_dropdown :selected').val();
console.log(state);
});
})
但是当我选择其中一个选项时,什么也没有发生,我知道ajax代码不存在,但是我现在想要的只是选择了其中一个选项时在控制台中看到某些内容.
But when i select one of the options nothing happens, I know the ajax code is not there but all i want for now is to see something in console when one of the options is selected.
我在这里想念什么?
这就是选择的样子
<select class="input-block-level chzn-select hiring_stage_dropdown" id="hiring_stage_dropdown" name="application_stage">
<option value="">Hiring stage</option>
<option value="3">Manager Step 1</option>
<option value="4">Manager Step 2</option>
</select>
推荐答案
通过jquery-ujs内置到Rails中时,从select下拉列表中选择项目时执行AJAX调用.
Executing an AJAX call when selecting an item from a select dropdown is built in to Rails via jquery-ujs.
首先,请确保您的Gemfile中有gem 'jquery-rails'
,在application.js清单文件中有//= require jquery_ujs
(默认情况下它们都在其中).
First, make sure you have gem 'jquery-rails'
in your Gemfile and //= require jquery_ujs
in your application.js manifest file (they are both there by default).
然后将data-remote
,data-url
和data-method
属性添加到您的选择中. jquery-url将序列化select的值并发出请求.您的select_tag
代码可能类似于:
Then add data-remote
, data-url
, and data-method
attributes to your select. jquery-url will serialise the value of the select and make the request. Your select_tag
code might look like:
<%= select_tag(
'application_stage',
options_for_select(
application.job.hiring_procedure.hiring_procedure_stages.map{ |p| [p.name, p.id] }
),
prompt: "Hiring stage",
class: 'input-block-level chzn-select hiring_stage_dropdown',
id: 'hiring_stage_dropdown',
data: {
remote: true,
url: '/your_path',
method: 'get'
}
) %>
当选择了一个值,jQuery的UJS将使
When a value is selected, jquery-ujs will make a GET
request to /your_path?application_stage=:selected_value
. You can then handle this in a js.erb response.
这篇关于Rails-通过选择下拉菜单执行Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!