【发布时间】:2015-12-04 13:36:13
【问题描述】:
我有一个带有电影数据库的 django 项目,并且希望我的搜索框能够简单地实现 typeahead.js 给我的自动完成功能。我之所以使用它是因为它的模板功能,并且因为它非常适合我用于样式的 Bootstrap。
urls.py
url(r'^get_movie/$', views.get_movie, name = 'get_movie')
views.py
def get_movie(request):
results = []
q = request.GET['q']
movies = Movie.objects.filter(title__icontains = q)
results = [ {movie.id: movie.name} for movie in movies ]
data = json.dumps(results)
return HttpResponse(data, content_type = 'application/json')
HTML 搜索框
<input id="searchBox" type="text" class="form-control input-lg typeahead" placeholder="Search a movie..." name="q"></input>
显然我已经包含了 jQuery、Bootstrap 和 typeahead.js。
上面是除了实现 typeahead.js 的 javascript 之外的所有必要代码
这是来自官方网站的示例,但我不知道我需要应用哪些修改才能从我的数据库中动态获取结果并将它们显示在自动完成列表中:
<script type="text/javascript">
$('.typeahead').typeahead(null, {
name: 'best-pictures',
display: 'value',
source: bestPictures,
templates: {
empty: [
'<div class="empty-message">',
'unable to find any Best Picture winners that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div><strong>{{value}}</strong> – {{year}}</div>')
}
});
</script>
提示:我很确定我需要使用 Ajax 来获取“源”列表,但我尝试过但无法做到。
【问题讨论】:
标签: javascript jquery django twitter-bootstrap typeahead.js