简体   繁体   English

从远程脚本中获取数据

[英]Fetching data from a remote script

I need to fetch the data dynamically (as the user types) from my database. 我需要从数据库中动态获取数据(作为用户类型)。 I had tried looking at the typeahead examples, but I do not understand how could I implement the remote implementation. 我曾尝试查看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)
    });

This requires the array states to be present locally. 这要求阵列states在本地存在。 But I need to get the data from my server side script. 但是我需要从服务器端脚本中获取数据。 How could I do this? 我该怎么办?

To use a remote datasource, it is recommended that you also use the bloodhound engine. 要使用远程数据源,建议您还使用猎犬引擎。

You will want to define your bloodhound instance, setting a remote option: 您将要定义您的猎犬实例,设置一个远程选项:

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

In this instance I've created an options hash, that holds the configuration of my remote source: 在这种情况下,我创建了一个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
        };
    });
  }
};

In it, I define the url for my remote source, how to handle the query, and how to return the data for consumption by the typeahead. 在其中,我定义了远程源的url,如何处理查询以及如何返回数据以供预输入使用。

Once I define my bloodhound instance, I then initialize it: 一旦定义了猎犬实例,就将其初始化:

taSource.initialize(true);

I then define my typeahead object to use the bloodhound instance: 然后,我定义我的typeahead对象以使用猎犬实例:

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

Here is a link to a jsFiddle demonstrating the basic use of remote sources. 这是jsFiddle的链接,展示了远程源的基本用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM