Javascript Rails如何在选择下拉选项后通过Ajax更新索引视图
我有一个带有“dept”属性的产品模型。该模型包括一个部门列表。在我看来,这是一个包含所有部门类型的下拉列表。在从下拉列表中选择某个部门后,我正在尝试刷新页面。我更喜欢通过AJAX进行更新,但现在我会使用普通的页面引用 我的模型Javascript Rails如何在选择下拉选项后通过Ajax更新索引视图,javascript,ruby-on-rails,ajax,drop-down-menu,filtering,Javascript,Ruby On Rails,Ajax,Drop Down Menu,Filtering,我有一个带有“dept”属性的产品模型。该模型包括一个部门列表。在我看来,这是一个包含所有部门类型的下拉列表。在从下拉列表中选择某个部门后,我正在尝试刷新页面。我更喜欢通过AJAX进行更新,但现在我会使用普通的页面引用 我的模型 class Product < ActiveRecord::Base attr_accessible :dept, :price, :title DEPT_TYPES = ["Baby","Beauty"] end 类产品
class Product < ActiveRecord::Base
attr_accessible :dept, :price, :title
DEPT_TYPES = ["Baby","Beauty"]
end
类产品
我的控制器:
class StoreController < ApplicationController
def index
@title= "Home"
@products = Product.order(:premium)
@baby , @beauty = [], []
@products.each do |product|
@baby << product if product.dept == 'Baby'
@beauty << product if product.dept == 'Beauty'
end
respond_to do |format|
format.html # index.html.erb
format.js # index.js.erb
format.json { render json: @products }
end
end
class StoreController
您可以使用简单的ajax jQuery函数:
$(".filter").change(function(){
var value = $(this).val()
$.ajax({
url: <%= stores_path(:json) %>,
type: 'GET',
data: value,
success: function(data){
$("#products_list").html(data.products)
}
})
})
$(“.filter”).change(函数(){
var值=$(this.val()
$.ajax({
网址:,
键入:“GET”,
数据:价值,
成功:功能(数据){
$(“#产品列表”).html(data.products)
}
})
})
您有两种方法可以做到这一点:
第一个是从服务器发送,例如JSON和所有产品。或者,您可以在视图中创建“.js.erb”文件,并在其中处理操作。我在哪里包括:remote=>true语法以指示这是一个ajax调用?在上面的代码中,您不应该添加remote:true。更改选择框后,将转到更改回调。然后在那里执行ajax请求。
$(".filter").change(function(){
var value = $(this).val()
$.ajax({
url: <%= stores_path(:json) %>,
type: 'GET',
data: value,
success: function(data){
$("#products_list").html(data.products)
}
})
})