1

我是 Rails 和 javascript 的新手,我一生都无法让它发挥作用。所以我正在尝试使用 bootstraps 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我转储我的 javascripts 的文件。

在那个文件中我有

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

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

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

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

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

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

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

4

1 回答 1

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);
});
于 2013-05-06T15:50:07.373 回答