我正在使用typeahead.js。
当我从apiController获取数据时,它看起来像这样:
["JobName1", "JobName1", "akhsfkh"]
当它通过此代码时:
$(function() {
var projectNumbers = $.getJSON("api/Project/GetAllNumbers")
.done(function(result) {
console.log(result);
return result; // ["JobName1", "JobName1", "akhsfkh"] is here
})
.fail(function(jqXHR, textStatus, err) {
alert('Error: ' + err);
});
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});
cb(matches);
};
};
$('#jobNumber').typeahead({
hint: true,
minLength: 2,
highlight: true,
},
{
name: 'projects',
source: substringMatcher(projectNumbers.serializeArray()),
});
});
我的输入框显示前面的类型,但可用数据是:
JobName1, JobName1, akhsfkh
substringMatcher函数没有改变它。
有什么建议吗?
答案 0 :(得分:1)
你必须存储结果,并在回调中完成其余的工作。
var projectNumbers;
$.getJSON("http://jsbin.com/heyobi/1.json")
.done(function (result) {
projectNumbers = result;
initTypeahead();
})
.fail(function (jqXHR, textStatus, err) {
alert('Error: ' + err);
});
var substringMatcher = function (strs) {
......
});
function initTypeahead() {
$('.typeahead').typeahead({
hint: true,
minLength: 2,
highlight: true,
}, {
name: 'projects',
source: substringMatcher(projectNumbers),
});
}
这是DEMO