执行自动完成功能。在控制器format.json
中返回一个名称数组。从json
我获取自动完成的值。但是当我开始输入输入时,然后在日志中我有:
Started GET "/search.json" for 127.0.0.1 at 2017-03-30 09:41:28 +0300
Processing by PagesController#search as JSON
(3.1ms) SELECT "items"."name" FROM "items" WHERE (name LIKE '%%')
Completed 200 OK in 34ms (Views: 19.2ms | ActiveRecord: 3.1ms)
问题是params[:q]
(在控制器中)即将出现nil
。
在控制器:
def search
@words = Item.where("name LIKE '%#{params[:q]}%'")
respond_to do |format|
format.html
format.json { render json: @words.pluck(:name) }
end
end
JS :
$(function(){
$('input[name="q"]').autoComplete({
minChars: 1,
source: function(term, response){
$.getJSON('/search.json', function (data) {
term = term.toLowerCase();
var matches = [];
for (i = 0; i < data.length; i++)
if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
response(matches.slice(0,5));
});
}
});
});
.erb
<input id="hero-demo" autofocus type="text" name="q" style="width:100%;max-width:600px;outline:0">
使用插件autocomplete
P.S。在客户端自动完成工作正常。
答案 0 :(得分:1)
将术语作为查询参数传递:
$(function(){
$('input[name="q"]').autoComplete({
minChars: 1,
source: function(term, response) {
term = term.toLowerCase();
$.getJSON('/search.json?q='+ term, function (data) {
var matches = [];
for (i = 0; i < data.length; i++)
if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
response(matches.slice(0,5));
});
}
});
});