在我的ASP.NET核心应用程序中,我有一个cshtml页面,在那里我尝试使用Twitter提前输入。这是我的标记:
<div id="type-ahead">
<input class="twitter-typeahead form-control" id="typeLocation" type="text" />
</div>以下是html输入的Javascript:
var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// 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)) {
matches.push(str);
}
});
cb(matches);
};
};
var locations = $.get('/Home/getlocationlist', function (data) {
});
$('#type-ahead .twitter-typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'locations',
source: substringMatcher(locations)
});我的问题是如何获取预输入的数据源。这是我的jQuery get:
var locations = $.get('/Home/getlocationlist', function (data) {});这是$.get检索的控制器函数:
public ActionResult GetLocationList()
{
var list = ExecuteRows("SELECT LocationName FROM Location ORDER BY LocationName");
var locations = list.SelectMany(x => x.Values);
return Ok(locations);
}$.get函数返回数据并将其分配给location。问题是数据返回为一个数组,如下所示
{["Location 1","Location 2","Location 3"]}但是,当我开始键入时,typeahead开始显示多行,其中每一行都显示上面提到的数组。我试图弄清楚如何正确地处理来自控制器方法的数据到typeahead。
谢谢!
发布于 2020-12-03 07:44:11
当我开始键入时,
开始显示多行,其中每一行都显示上面提到的数组。
要解决上述问题,请尝试修改代码,将初始化the的代码放入Ajax成功回调函数中,如下所示。
var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// 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)) {
matches.push(str);
}
});
cb(matches);
};
};
$.get('/Home/getlocationlist', function (data) {
var locations = data;
$('#type-ahead .twitter-typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'locations',
source: substringMatcher(locations)
});
});测试结果

https://stackoverflow.com/questions/65094836
复制相似问题