我正在使用我的rails应用程序中的搜索表单。这就是我现在所拥有的:
我的观点:
<%= form_tag search_suggestions_path, method: 'get', id: 'all-games-search' do %>
<%= text_field_tag :games_search, (params[:games_search].present? ? params[:games_search] : nil),
class: 'search-input', placeholder: 'Search games...', autocomplete: 'off' %>
<ul id="results"></ul>
<%= button_tag name: nil, class: 'submit-button' %>
<% end %>
控制器:
def search_suggestions
query = params[:games_search]
results = if query.present?
response = []
Game.where('title ILIKE ?', query.to_s).each do |game|
obj = {id: game.id, title: "#{query}"}
response << obj
end
response
else
[]
end
render json: results
end
js:
$('#games_search').bind('change input paste', function() {
var val = $(this).val();
$.get('/search_suggestions?games_search=' + val, function (data) {
$('#results').empty().show();
$.each(data, function(index, results) {
$('#results').append('<li>' + results.title + '</li>').click(function () {
location.href = '/games/' + results.id;
});
});
});
});
这段代码有效,但只有当我输入整个游戏的标题时,它才会给我结果。我需要的是,当在搜索输入中输入游戏标题的前几个符号时,显示搜索结果。谢谢你。