gpt4 book ai didi

jquery - 在 typeahead.js 中使用预取而不是本地时出现问题

转载 作者:行者123 更新时间:2023-12-01 05:50:19 25 4
gpt4 key购买 nike

我的代码可以很好地处理本地数据,但如果我将本地数据复制到 json 文件并使用预取选项,它就不起作用,它只会返回一个未定义的列表。

我想使用预取数据并监听自定义事件句柄 typeahead:selected 来填充多个输入字段。有什么建议来解决这个问题吗?谢谢。

我的代码在这里:

  <form>
<input type="text" class="typeahead" id="subject_label" /><br/>
<input type="text" id="subject_id" /><br/>
</form>
var s = [{"id":"1234","label":"fish"},{"id":"5678","label":"histo"}]

var labels = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.label);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
// local option is working
// local: s
// If using prefetch url option with exactly same dataset, the code is broken, I'm
//sure the url format is correct.
prefetch: '/sample.json'

});

labels.initialize();

var subjectLabelTypeahead = $('#subject_label.typeahead');
var subjectIdTypeahead = $('#subject_id');

// Initialise typeahead
subjectLabelTypeahead.typeahead({
highlight: true
}, {
name: 'label',
displayKey: 'label',
source: labels.ttAdapter()
});

// Set-up event handlers so that the ID is auto-populated when select label
var subjectLabelItemSelectedHandler = function (e, datum) {
subjectIdTypeahead.val(datum.id);
};

subjectLabelTypeahead.on('typeahead:selected', subjectLabelItemSelectedHandler);

最佳答案

您的“预取”值应引用 javascript 对象而不是 URL 字符串(请参阅文档 here )。

尝试将其更改为:

var labels = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.label);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/sample.json',
filter: function(items) {
return $.map(items, function(item) {
return {
label: item.label,
id: item.id };
});
}
});

关于jquery - 在 typeahead.js 中使用预取而不是本地时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22946831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com