我正在尝试将JQuery Typeahead plugin与AJAX一起使用,但没有看到任何搜索结果。 AJAX请求返回正常,但不显示任何内容。
下面的示例使用Open Brewery Search API查找啤酒厂,并且已将typeahead模板设置为显示结果对象中的name属性。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.css">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<form>
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="js-typeahead"
name="q"
type="search"
autocomplete="off"
placeholder="try: cooper">
</div>
<div class="typeahead__button">
<button type="submit">
<span class="typeahead__search-icon"></span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.js"></script>
<script>
$.typeahead({
input: ".js-typeahead",
order: "asc",
dynamic: true,
delay: 300,
template: "<p>{{name}}</p>",
source: {
breweries: {
ajax: function(query) {
return {
url: "https://api.openbrewerydb.org/breweries?by_name=" + query
}
}
}
}
});
</script>
</body>
</html>
答案 0 :(得分:0)
您需要使用filter: false
。 See github issue.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.css">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<form>
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="js-typeahead"
name="q"
type="search"
autocomplete="off"
placeholder="try: cooper">
</div>
<div class="typeahead__button">
<button type="submit">
<span class="typeahead__search-icon"></span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.10.6/jquery.typeahead.js"></script>
<script>
$.typeahead({
input: ".js-typeahead",
order: "asc",
dynamic: true,
filter: false,
delay: 300,
template: "<p>{{name}}</p>",
source: {
breweries: {
ajax: function(query) {
return {
url: "https://api.openbrewerydb.org/breweries?by_name=" + query
}
}
}
}
});
</script>
</body>
</html>