rails中用于动态组合框选择的Ajax

Ajax for dynamic combo box selection in rails

本文关键字:选择 Ajax 组合 用于 动态 rails      更新时间:2023-09-26

我在一个页面中有两个组合框。如果我选择第一个组合框选项,那么在第二个组合框中,它会自动显示与第一个选择的选项相关的选项,而不会刷新页面。

我的模型:

class Location < ActiveRecord::Base
  scope :active, -> { where(:is_active => true) }
  has_many :stores
end
class Store < ActiveRecord::Base
  scope :active, -> { where(:is_active => true) }
  belongs_to :location
  has_many :companies
end
class Company < ActiveRecord::Base
  belongs_to :store
  scope :active, -> { where(:is_active => true) }
end

在我的HAML视图表单

  .field
    .ui-widget
      = f.label :location
      = select_tag(:location, options_from_collection_for_select(Location.active, :id, :name), :prompt => "Select location")
  .field
    .ui-widget
      = f.label :store
      = f.select :store_id, Store.active.collect { |s| [s.name, s.id] }, :prompt => "Select store"

我知道这是可能的通过使用Ajax,我也搜索了许多Ajax,但它是php,我不明白如何使用。我以前从未使用过Ajax。请帮帮我……提前感谢。:)

首先要明白一件事,AJAX与php或rails无关,它是一个javascript函数调用

现在根据你的问题在我的HAML视图表单

.field
.ui-widget
  = f.label :location
  = select_tag(:location, options_from_collection_for_select(Location.active, :id, :name), :prompt => "Select location", onchange: "change_store(this)")
.field
.ui-widget#store_list
  = f.label :store
  = f.select :store_id, Store.active.collect { |s| [s.name, s.id] }, :prompt => "Select store"
function change_store(select_tag){
  value1 = $(select_tag).val()
  $.ajax({
    url: "controller_name/mehuod_name",
    data: {data1: value1}
  })
 }

现在把route放到route中。Rb文件并在相应的控制器中创建方法来查找商店列表,然后您可以使用jquery替换"select_lit"下的HTML,简单的

希望这是你所期望的