Django、jQuery 和自动完成 [英] Django, jQuery, and autocomplete
问题描述
经过一些广泛的研究(谷歌搜索),我找不到关于如何使用 Django 和 jQuery 设置自动完成的当前教程.似乎有各种各样的插件,而且似乎没有一致性或标准来决定使用哪些或何时使用.
After some extensive research (Googling), I cannot find a current tutorial on how to set up autocomplete using Django and jQuery. There appears to be a variety of plugins and there appears to be no consistency or standard about which to use or when.
我不是 Django 或 jQuery 的专业人士,但需要一个有据可查且易于使用的自动完成解决方案.
I'm not a pro at either Django or jQuery, but need an autocomplete solution that is well documented and fairly simple to utilize.
建议?
推荐答案
如果您想从 django 模型中进行搜索,那么类似于:
If you're looking to search from within your django models then something like:
from django.utils import simplejson
def autocompleteModel(request):
search_qs = ModelName.objects.filter(name__startswith=request.REQUEST['search'])
results = []
for r in search_qs:
results.append(r.name)
resp = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');'
return HttpResponse(resp, content_type='application/json')
对于 jQuery 自动完成和调用:
For the jQuery autocomplete and call:
function searchOpen() {
var search = $('#txtSearch').val()
var data = {
search: search
};
$.ajax({
url: '/search.json',
data: data,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'searchResult'
});
}
function searchResult(data) {
$( "#txtSearch" ).autocomplete ({
source: data
});
}
最后将所有内容连接到您的输入表单上,将具有以下内容:
Finally to connect it all on your input form would have something like:
<input type="text" name="search" id="txtSearch" onkeyup="searchOpen()" />
注意,除了常用的 jQuery 之外,这里还使用了 Jquery UI.
Note, this is using Jquery UI as well in addition to stock jQuery.
这篇关于Django、jQuery 和自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!