获取bootstraps typeahead功能以使用rails中的数据库查询

时间:2013-05-06 12:39:14

标签: javascript json ruby-on-rails-3

我是rails和javascript的新手,但对于我的生活来说,无法让它发挥作用。所以我试图使用bootstraps typeahead获得自动完成功能,但一直遇到障碍。

首先我从这个site尝试一个例子,一切都很好。在我的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的文件,我转储了我的javascripts。

在那个文件中我有

var colors = ["red", "blue", "green", "yellow", "brown", "black"];

$('#search').typeahead({source: colors});

所以现在当我打开我的视图时,我有一个很好的文本字段,其中包含bootstraps typeahead

但是我不想使用静态数组来查找值。我想访问数据库列,并查找该列中的所有值(这些值都是唯一的),理想情况下提供附带的id到输入字段。所以我谷歌走了,不幸的是第一次同时尝试了解javascript。

这个问题,或者一个非常相似的问题,已被问到这里几十次了,但不知怎的,这些问题都没有让我的代码工作。

有些答案提示this脚本,但是当我复制代码并将其保存为bootstrap-typeahead.js时,custom.js文件中正常工作的js停止工作(我做错了吗?) 。

所以我尝试的是bootstraps网站上建议的最低限度工作解决方案。我正在尝试的代码是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输出是什么?我在哪里错了?

1 个答案:

答案 0 :(得分:1)

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

尝试将$.get替换为$.getJSON。这将告诉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);
});