【问题标题】:Fetching data from a remote script从远程脚本获取数据
【发布时间】:2016-04-05 08:59:14
【问题描述】:

我需要从我的数据库中动态获取数据(作为用户类型)。我曾尝试查看typeahead 示例,但我不明白如何实现远程实现。

<div id="remote">
  <input class="typeahead" type="text" placeholder="Oscar winners for Best Picture">
</div>

$('#the-basics .typeahead').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      name: 'states',
      source: substringMatcher(states)
    });

这要求数组states 存在于本地。但我需要从我的服务器端脚本中获取数据。我怎么能这样做?

【问题讨论】:

  • 你应该试试这个例子 - twitter.github.io/typeahead.js/examples/#remote
  • @Dekay source: bestPictures 这里是什么?
  • 这是上面创建Bloodhound 对象的变量的名称...这个Bloodhound 对象描述了您的数据将如何被访问
  • 您还需要将 typeahead budle 包含为 js 资源 typeahead.bundle.js (bloodhound.js + typeahead.jquery.js) 它需要 jQuery 1.9+
  • @aashna 你找到答案了吗?

标签: javascript typeahead.js twitter-typeahead


【解决方案1】:

要使用远程数据源,建议您同时使用 Bloodhound 引擎。

你需要定义你的寻血犬实例,设置一个远程选项:

var taSource = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  identify: function(obj) {
    return obj.Value;
  },
  remote: todos
});

在这种情况下,我创建了一个 options 哈希,它保存了我的远程源的配置:

var urlRoot = '//jsonplaceholder.typicode.com';
var todos = {
  url: urlRoot + '/todos',
  prepare: function(query, settings) {
    settings.url += '?q=' + query;
    return settings;
  },
  filter: function(data) {
    return $.map(data, function(object) {
        return {
          Id: object.id,
          Value: object.title
        };
    });
  }
};

在其中,我定义了远程源的 url,如何处理查询,以及如何返回数据以供预先输入使用。

一旦我定义了我的 Bloodhound 实例,我就会对其进行初始化:

taSource.initialize(true);

然后我定义我的 typeahead 对象以使用 Bloodhound 实例:

$('#search-input').typeahead({
  hint: true,
  highlight: true,
  minLength: 3
}, {
  name: 'myMatches',
  source: taSource,
  display: 'Value'
});

这里是a link to a jsFiddle 演示远程源的基本用法。

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 1970-01-01
    相关资源
    最近更新 更多