Sam*_*ley 5 javascript django jquery twitter-bootstrap typeahead.js
我有一个带有电影数据库的 django 项目,并且希望我的搜索框能够简单地实现 typeahead.js 提供的自动完成功能。我使用它是因为它的模板功能,并且它与我用于样式设计的 Bootstrap 非常契合。
\n\nurls.py
\n\nurl(r\'^get_movie/$\', views.get_movie, name = \'get_movie\')\nRun Code Online (Sandbox Code Playgroud)\n\n视图.py
\n\ndef get_movie(request):\n results = []\n q = request.GET[\'q\']\n movies = Movie.objects.filter(title__icontains = q)\n results = [ {movie.id: movie.name} for movie in movies ]\n data = json.dumps(results)\n return HttpResponse(data, content_type = \'application/json\')\nRun Code Online (Sandbox Code Playgroud)\n\nHTML 搜索框
\n\n<input id="searchBox" type="text" class="form-control input-lg typeahead" placeholder="Search a movie..." name="q"></input>\nRun Code Online (Sandbox Code Playgroud)\n\n显然我已经包含了 jQuery、Bootstrap 和 typeahead.js。
\n\n上面是除了实现 typeahead.js 的 javascript 之外的所有必要代码
\n\n这是官方网站上的示例,但我不知道需要进行哪些修改才能从数据库动态获取结果并将其显示在自动完成列表中:
\n\n<script type="text/javascript">\n $(\'.typeahead\').typeahead(null, {\n name: \'best-pictures\',\n display: \'value\',\n source: bestPictures,\n templates: {\n empty: [\n \'<div class="empty-message">\',\n \'unable to find any Best Picture winners that match the current query\',\n \'</div>\'\n ].join(\'\\n\'),\n suggestion: Handlebars.compile(\'<div><strong>{{value}}</strong> \xe2\x80\x93 {{year}}</div>\')\n }\n });\n</script>\nRun Code Online (Sandbox Code Playgroud)\n\n提示:我很确定我需要使用 Ajax 来获取“源”列表,但已经尝试过但无法做到这一点。
\n我们最终使用了朋友给我们的这个解决方案,效果很好:
<script type="text/javascript">
$(document).ready(function(){
var queryMovies = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 20,
rateLimitWait: 800,
remote: {url:'/get_movie/?q=%QUERY', wildcard: '%QUERY'}
});
queryMovies.initialize();
$('#remote .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 2,
},
{
name: 'queryMovies',
display: 'value',
source: queryMovies.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No hay resultados con la consulta',
'</div>'
].join('\n'),
suggestion: function(data) {
var url = "{% url 'movie' '00000' %}"
url = url.replace('00000', data.id);
return '<div><p><a href="' + url + '">' + data.title + '</a></p></div>';
}
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1759 次 |
| 最近记录: |