[英]Fetching data from a remote script
我需要從數據庫中動態獲取數據(作為用戶類型)。 我曾嘗試查看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
在本地存在。 但是我需要從服務器端腳本中獲取數據。 我該怎么辦?
要使用遠程數據源,建議您還使用獵犬引擎。
您將要定義您的獵犬實例,設置一個遠程選項:
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,如何處理查詢以及如何返回數據以供預輸入使用。
一旦定義了獵犬實例,就將其初始化:
taSource.initialize(true);
然后,我定義我的typeahead對象以使用獵犬實例:
$('#search-input').typeahead({
hint: true,
highlight: true,
minLength: 3
}, {
name: 'myMatches',
source: taSource,
display: 'Value'
});
這是jsFiddle的鏈接,展示了遠程源的基本用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.