[英]Ruby On Rails : How to retrieve data from database on ajax request
我有一個表單,在輸入字段中鍵入內容時,我需要從categorys表中獲取包含該關鍵字的所有類別。
我有兩個控制器,即。 書籍和類別。
主要目的是添加一本書並選擇一個類別。
我需要使用ajax來執行此操作。
我已經嘗試了很多。 但是它們都不起作用。
我已經包括了jquery和所有需要的腳本。 但仍然顯示出來。
有人可以幫我嗎?
JQUERY
$('#book_search').keyup(function(){
$.ajax({
type:"GET",
url:"books/new",
dataType:"json",
data: {keyword: '$("input[name'search']").val()},
success:function(result){
alert(result);
}
})
})
HTML
<%= simple_form_for :book, url: books_path do |f| %>
<p> <%= f.label :name %> <%= f.text_field :name %> </p>
<p> <%= f.input :category, collection: @categories, prompt: "Select Category" %></p>
<p> <%= f.label :search %> <%= f.text_field :search %> </p>
<p> <%= f.submit %></p>
<% end %>
class BooksController < ApplicationController
def index
@books = Book.all
@categories = Category.all
end
def new
@categories = Category.all
end
def create
@book = Book.new(book_params)
@book.save
redirect_to @book
end
def show
@book = Book.find(params[:id])
@categories = Category.all
end
def show_categories
@category = Category.find(params[:id])
end
private
def book_params
params.require(:book).permit(:name, :category)
end
end
有許多實現自動完成功能的庫,包括2種最流行的,自動完成功能和預輸入類型。
但是,顯然每個庫都是額外的開銷,因此如果您想自己實現它,當然可以。
要考慮的一些事情:
@categories
,因此我會猶豫使用相同的實例變量返回搜索結果,因此我將其命名為不同的名稱。 鑒於此,您可以在視圖(窗體)中執行類似的操作
<div id="book_create">
<%= simple_form_for :book, url: books_path do |f| %>
<%= f.input :name %>
<%= f.input :category_id, as: :hidden %>
<%= f.input :category_search, as: :string, input_html: {class: "book_search"} , autocomplete: false %>
<div id="cat_search"></div>
<%= f.submit %>
<% end %>
</div>
<style>
#categories { width: 200px; max-height: 220px; overflow: scroll; box-shadow: 1px 1px 4px rgba(158, 158, 158, 0.43); list-style: none; padding: 0; }
#categories li:nth-of-type(odd) { background-color: rgb(238, 247, 255); }
#categories li { cursor: pointer; }
</style>
包括簡單的CSS,可以很好地解決問題。
$('.book_search').keyup(function(){
var q = $(this).val();
$.ajax({
type: "GET",
url: "/categories/search",
dataType: "json",
data: {'keyword': q},
success: function(result){
$("#categories").remove();
$("#cat_search").after('<ul id="categories"></ul>');
render = true;
$("#categories").on("click", "li", function(){
$("#book_category_id").val($(this).data('id'));
$(".book_search").val($(this).text());
$("#categories").remove();
});
for(term in result){
render = false;
$("#categories").append("<li data-id="+result[term].id+">" + result[term].keyword + "</li>");
}
}
})
});
在此JS中,實際上沒有任何魔術,只是簡單的jQuery。 您可以抓住用戶輸入並以用戶輸入作為查詢來調用url,如果返回了查詢,則刪除任何先前的顯示列表,然后為用戶建立一個顯示列表(ul),並顯示所有可能的結果。 單擊您選擇的結果會做兩件事,a。)從我們從結果集中注入的數據屬性中添加id,b。)清除用戶鍵入的輸入字段,並將其替換為所選結果的全名。
class CategoriesController < ApplicationController
before_action :set_category, only: [:show, :edit, :update, :destroy]
respond_to :json, :html
def search
@cat_search_results = Category.where("keyword LIKE LOWER(?)", "%#{params[:keyword].downcase}%")
respond_with(@cat_search_results, :include => :status)
end
end
#/categories/search.json.jbuilder
json.array!(@cat_search_results) do |category|
json.extract! category, :id, :keyword
end
resources categories do
collection do
get :search
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.