Javascript 从远程脚本获取数据

Javascript 从远程脚本获取数据,javascript,typeahead.js,twitter-typeahead,Javascript,Typeahead.js,Twitter Typeahead,我需要从数据库中动态地获取数据(根据用户类型)。我试着看了看前面的typeahead 示例,但我不明白如何实现远程实现 <div id="remote"> <input class="typeahead" type="text" placeholder="Oscar winners for Best Picture"> </div> $('#the-basics .typeahead').typeahead({ hint: true,

我需要从数据库中动态地获取数据(根据用户类型)。我试着看了看前面的
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)
    });

$(“#basics.typeahead”).typeahead({
提示:没错,
推荐理由:没错,
最小长度:1
},
{
名称:“州”,
来源:子字符串匹配器(状态)
});

这要求数组
状态
在本地出现。但是我需要从服务器端脚本获取数据。我如何才能做到这一点?

要使用远程数据源,建议您也使用侦探犬引擎

您需要定义您的猎犬实例,设置远程选项:

var taSource = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  identify: function(obj) {
    return obj.Value;
  },
  remote: todos
});
在本例中,我创建了一个
options
hash,它保存远程源的配置:

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、如何处理查询以及如何返回数据供typeahead使用

一旦我定义了我的猎犬实例,我就会初始化它:

taSource.initialize(true)

然后,我定义我的typeahead对象以使用嗜血犬实例:

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

这里演示了远程源的基本用法。

您应该试试这个例子-@Dekay什么是
source:bestPictures
?这是上面创建
猎犬对象的变量的名称。。。这个
Bloodhound
对象描述了如何访问您的数据。您还需要将typeahead budle作为js资源
typeahead.bundle.js(Bloodhound.js+typeahead.jquery.js)
它需要jquery 1.9+@aashna您找到答案了吗?