获得bootstrap typeahead功能,以便在rails中处理数据库查询

Getting bootstraps typeahead functionality to work with database queries in rails

本文关键字:rails 处理 数据库 查询 typeahead bootstrap 功能 获得      更新时间:2023-09-26

我是rails和javascript的新手,对于我的生活不能得到这个工作。所以我尝试使用bootstrap typeahead来获得自动完成功能,但总是碰到障碍。

所以首先我尝试从这个网站的一个例子,一切都工作得很好。在view中,我有

<input input="text" name="query" id="search" autocomplete="off" />

application.js中,我有

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require twitter/bootstrap
//= require jquery-fileupload/basic
//= require_tree .

在我的javascript资产文件夹中,我有一个名为custom.js的文件,我在那里转储我的javascript。

文件中有

var colors = ["red", "blue", "green", "yellow", "brown", "black"];
$('#search').typeahead({source: colors});

所以现在,当我打开我的视图,我有一个很好的文本字段与bootstrap typeahead功能。

但是我不想使用静态数组来查找值。我想访问一个数据库列,并查找该列的所有值(这些值都是唯一的),理想情况下,为输入字段提供伴随的id。所以我谷歌离开,不幸的是,试图理解javascript的第一次在同一时间。

这个问题,或者一个非常类似的问题,已经在这里被问了几十次了,但不知何故,没有一个能让我的代码工作。

一些答案建议这个脚本,但是当我复制代码并将其保存为bootstrap-typeahead.js我正常工作的js从custom.js文件停止工作(我做错了吗?)。

所以我尝试的是一个最低限度的工作解决方案,建议在bootstrap网站。我正在尝试的代码是custom.js

$('#search').typeahead({
    source: function (query, process) {
        $.get('sources', { query: query }, function (data) {
            return process(JSON.parse(data));
        });
    }
});

控制器的动作是这样的

  def index
    if params[:query]
      @sources = Source.find(:all, :conditions => ['name LIKE ?', "%#{params[:query]}%"])
    else
      @sources = Source.all
    end
    respond_to do |format|  
      format.html # index.html.erb
      format.json { render json: @sources }
    end
  end

所以,我想我现在的理解能力已经到了极限。当我呈现视图并输入输入字段时,控制台显示

Started GET "/sources?query=s" for 127.0.0.1 at 2013-05-06 12:30:10 +0000
Processing by SourcesController#index as */*
  Parameters: {"query"=>"s"}
  Source Load (0.9ms)  SELECT "sources".* FROM "sources" WHERE (name LIKE '%s%')
  Rendered sources/index.html.erb within layouts/application (0.2ms)
  Rendered layouts/_shim.html.erb (0.1ms)
  Rendered layouts/_header.html.erb (2.8ms)
Completed 200 OK in 194ms (Views: 189.8ms | ActiveRecord: 0.9ms)

太棒了,我的功能是调用正确的操作和正确的查询…但是它会返回任何东西吗?输入字段中没有显示任何内容(在名称列中有一条记录的值KG-01),我怎么能看到函数的json输出是什么?我哪里出错了?

从日志中您可以看到您的请求被作为HTML处理并呈现索引,而不是返回JSON。

尝试用$.getJSON替换$.get。这将告诉jQuery发出JSON请求,并为您解析JSON结果:

$.getJSON('sources', { query: query }, function (data) {
  // this would print the data to the firefox/chrome javascript console
  console.log(data);
  // the data coming back from your rails action is an array of `Source`
  // records, but typeahead just wants the name.  You could either modify 
  // the server action to just return a list of names, or extract them here.
  var names = data.map(function (source) { return source.name; });
  // Note there is no need to `return` here, as it would be returning from
  // the anonymous callback function, not `source`.
  process(names);
});