我正在尝试构建一个搜索表单,但无法理解在我的具体情况下使用 UJS 的正确方法。我遇到的主要问题是,我无法弄清楚如何获取表单中选择的参数并执行查询,然后返回搜索结果。
我希望能够从使用下拉选择元素和日期字段的模型中选择多个“搜索条件”。选择搜索项来构建查询后,我想提交 POST 或 GET 请求,并返回结果并通过 ajax 显示在搜索表单下方的列表中,而无需重新加载页面。
目前,我有一个名为搜索的静态页面,其路由设置为:
match '/search', to: 'search#index'
index.html.erb
<h1>Search</h1>
<!-- search form -->
<div id="search">
<%= render 'form' %>
</div>
<!-- search results -->
<div id="results">
</div>
我有一个带有“索引”操作的 SearchController,它可以处理加载所有项目集合以放入使用 collection_select() 方法构建的搜索表单下拉菜单中。
搜索 Controller
class SearchController < ApplicationController
def index
# load up all the items to display as selectable search parameters to build query from
# Collections, Categories, Names
@collections = Collection.all
@categories = Category.all
@names = Name.all
end
def create
@collection = Collection.find(params[:collection][:id])
@category = Category.find(params[:category][:id])
@name = Name.find(params[:fullname][:id])
respond_to do |format|
format.html { redirect_to search_url }
format.js
end
end
end
我在部分中使用的表单:_form.htm.erb
<%= form_tag( {controller: "search"}, class: "search_form", remote: true) do %>
<%= label_tag("Categories: ") %>
<%= collection_select(:category, :id, @categories, :id, :name, {}, html_options = { multiple: false }) %>
<%= label_tag("Collections: ") %>
<%= collection_select(:collection, :id, @collections, :id, :title, {}, html_options = { multiple: false }) %>
<%= label_tag("Names: ") %>
<%= collection_select(:name, :id, @names, :id, :fullname, {}, html_options = { multiple: false }) %>
<%= submit_tag("Submit") %>
<% end %>
当我在页面中提交表单时,我在 Chrome 控制台中看到带有参数的 ajax 请求。我尝试在哈希中为 form_tag 提供一个操作,但它似乎无法找到路线,除非我在 paths.rb 文件中指定它。
例如,
<%= form_tag( {controller: "search", action: "create"}, class: "search_form", remote: true) do %>
问:如果我使用ajax,是否需要有特殊的路由?
问:如何将参数带入任何名称的 SearchController 操作中并对其执行某些操作?
我希望首先能够在结果 div 中将搜索查询项显示为文本,以便我知道该操作是如何工作的。我想我只会使用 js/jQuery 将提交到结果 div 的参数值附加到。
问:还有其他方法可以做这样的事情吗?
最佳答案
强烈建议采用这种方法: Search, Sort, Paginate with AJAX
顺便说一句,作者使用的 jquery 方法 .live() 已经过时,已被替换为 .delegate() jquery documentation .deleate()
关于javascript - rails : Need help building a basic AJAX search form and displaying results,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17725475/