我试图找到一个工作的twitter bootstrap typeahead元素的例子,将使ajax调用来填充它的下拉列表。
我有一个现有的工作jquery自动完成的例子,它定义了ajax url和如何处理回复
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
var options = { minChars:3, max:20 };
$("#runnerquery").autocomplete('./index/runnerfilter/format/html',options).result(
function(event, data, formatted)
{
window.location = "./runner/index/id/"+data[1];
}
);
..
我需要改变什么来转换这到typeahead的例子?
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
var options = { source:'/index/runnerfilter/format/html', items:5 };
$("#runnerquery").typeahead(options).result(
function(event, data, formatted)
{
window.location = "./runner/index/id/"+data[1];
}
);
..
我将等待“为typeahead添加远程源支持”问题得到解决。
我使用$().one()
为了解决这个问题;
当页面加载,我发送ajax到服务器,等待完成。
然后将结果传递给函数。$().one()是重要的。因为强制typehead.js附加到输入一次。
很抱歉写得不好。
(($) => {
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 states = [];
$.ajax({
url: 'https://baconipsum.com/api/?type=meat-and-filler',
type: 'get'
}).done(function(data) {
$('.typeahead').one().typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'states',
source: substringMatcher(data)
});
})
})(jQuery);
.tt-query, /* UPDATE: newer versions use tt-input instead of tt-query */
.tt-hint {
width: 396px;
height: 30px;
padding: 8px 12px;
font-size: 24px;
line-height: 30px;
border: 2px solid #ccc;
border-radius: 8px;
outline: none;
}
.tt-query { /* UPDATE: newer versions use tt-input instead of tt-query */
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.tt-hint {
color: #999;
}
.tt-menu { /* UPDATE: newer versions use tt-menu instead of tt-dropdown-menu */
width: 422px;
margin-top: 12px;
padding: 8px 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 8px;
box-shadow: 0 5px 10px rgba(0,0,0,.2);
}
.tt-suggestion {
padding: 3px 20px;
font-size: 18px;
line-height: 24px;
cursor: pointer;
}
.tt-suggestion:hover {
color: #f0f0f0;
background-color: #0097cf;
}
.tt-suggestion p {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<input class="typeahead" type="text" placeholder="where ?">
可以使用Bootstrap进行调用。当前版本没有任何源代码更新问题
麻烦更新Bootstrap的输入前数据源与后响应
,也就是说,bootstrap的源代码一旦更新,就可以再次修改。
请参考下面的例子:
jQuery('#help').typeahead({
source : function(query, process) {
jQuery.ajax({
url : "urltobefetched",
type : 'GET',
data : {
"query" : query
},
dataType : 'json',
success : function(json) {
process(json);
}
});
},
minLength : 1,
});
$('#runnerquery').typeahead({
source: function (query, result) {
$.ajax({
url: "db.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
},
updater: function (item) {
//selectedState = map[item].stateCode;
// Here u can obtain the selected suggestion from the list
alert(item);
}
});
//Db.php file
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'TableName');
$sql = $conn->prepare("SELECT * FROM TableName WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$Resut[] = $row["name"];
}
echo json_encode($Result);
}
$conn->close();
?>
我没有一个可行的例子,也没有一个非常清晰的解决方案,但让我告诉你我的发现。
如果你看一下TypeAhead的javascript代码,它是这样的:
items = $.grep(this.source, function (item) {
if (that.matcher(item)) return item
})
这段代码使用jQuery“grep”方法来匹配源数组中的元素。我没有看到任何可以在AJAX调用中挂钩的地方,所以没有一个“干净”的解决方案。
However, one somewhat hacky way that you can do this is to take advantage of the way the grep method works in jQuery. The first argument to grep is the source array and the second argument is a function that is used to match the source array (notice Bootstrap calls the "matcher" you provided when you initialized it). What you could do is set the source to a dummy one-element array and define the matcher as a function with an AJAX call in it. That way, it will run the AJAX call just once (since your source array only has one element in it).
这种解决方案不仅很棘手,而且还会出现性能问题,因为TypeAhead代码被设计为对每一次按键都进行查找(AJAX调用实际上应该只在每几次按键或在一定的空闲时间之后发生)。我的建议是尝试一下,但是坚持使用不同的自动补全库,或者如果遇到任何问题,只在非ajax的情况下使用它。