我在我的项目中进行了ajax搜索,但是在向jquery代码中添加链接时遇到了问题。我可以看到搜索结果,但我不知道如何到达结果页面。
我的js代码:
$(document).ready(function () {
$('#q').bind("change input paste", function(){
var val = $(this).val();
$.get( "/search_suggestions?query="+val, function(data) {
$('#results').empty();
$('#results').show();
$.each(data, function(index, result) {
$('#results').append('<li>'+result+'</li>');
$('#results').click(function () {
//do smth. on click
});
});
});
//do not display anything
});
});
观点:
<div>
<%= form_tag('#', method: 'get', id: 'header-search', class: 'navbar-form') do %>
<div class="input-group">
<%= text_field_tag(:q, (params[:q].present? ? params[:q] : nil), class: 'form-control', placeholder: 'Поиск', autocomplete: 'off') %>
<i aria-hidden="true" onclick="document.getElementById('header-search').submit();"></i>
<ul id="results">
</ul>
<div class="input-group-btn">
<button class="btn btn-default disabled"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
<% end %>
</div>
控制器:
def search_suggestions
query = params[:query]
results = if params[:query].present?
Doctor.where('name ILIKE ? OR surname ILIKE ?', "%#{query}%", "%#{query}%").select(:surname).collect(&:surname)
else
[]
end
render json: results
end
路线:
Rails.application.routes.draw do
...
get 'search_suggestions' => 'doctors#search_suggestions', as: :search_suggestions
end
感谢。