Django 的 Jquery 自动完成插件(Trey Piepmeier 解决方案)
因此,我的代码基于 Trey 的解决方案:
http://solutions.treypiepmeier.com/2009 /12/10/using-jquery-autocomplete-with-django/
脚本是:
<script>
$(function() {
$('#id_members').autocomplete('{{ object.get_absolute_url }}members/lookup', {
dataType: 'json',
width: 200,
parse: function(data) {
return $.map(data, function(row) {
return { data:row, value:row[1], result:row[0] };
});
}
}).result(
function(e, data, value) {
$("#id_members_pk").val(value);
}
);
}
);
</script>
views.py:
def members_lookup(request, pid):
results = []
if request.method == "GET":
if request.GET.has_key(u'q'):
value = request.GET[u'q']
# Ignore queries shorter than length 1
if len(value) > 2:
model_results = Member.objects.filter(
Q(user__first_name__icontains=value) | Q(user__last_name__icontains=value)
)
results = [ (x.user.get_full_name(), x.id) for x in model_results ]
json = simplejson.dumps(results)
print json
return HttpResponse(json, mimetype='application/json')
问题是:
它在初始查找后停止细化搜索结果。 例如:
如果我设置 len(value) > 2,在我输入第三个字符后,它会给我一个建议列表。但是,如果我继续输入第四个或第五个字符,建议列表不会改变。
关于这是为什么的任何建议?
So, I'm basing my code on Trey's solution on:
http://solutions.treypiepmeier.com/2009/12/10/using-jquery-autocomplete-with-django/
The script is:
<script>
$(function() {
$('#id_members').autocomplete('{{ object.get_absolute_url }}members/lookup', {
dataType: 'json',
width: 200,
parse: function(data) {
return $.map(data, function(row) {
return { data:row, value:row[1], result:row[0] };
});
}
}).result(
function(e, data, value) {
$("#id_members_pk").val(value);
}
);
}
);
</script>
The views.py:
def members_lookup(request, pid):
results = []
if request.method == "GET":
if request.GET.has_key(u'q'):
value = request.GET[u'q']
# Ignore queries shorter than length 1
if len(value) > 2:
model_results = Member.objects.filter(
Q(user__first_name__icontains=value) | Q(user__last_name__icontains=value)
)
results = [ (x.user.get_full_name(), x.id) for x in model_results ]
json = simplejson.dumps(results)
print json
return HttpResponse(json, mimetype='application/json')
The problem is:
It stops refining the search results after the initial lookup.
For example:
If I set len(value) > 2, after I type the 3rd character it will give me a list of suggestions. But if I keep on typing the 4th or 5th character, the list of suggestions doesn't change.
Any suggestions on why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于服务器端,我建议您查看 ajax selects 应用程序
For server side I recommend you take a look an ajax selects application
我通过从视图端传递一个字符串来解决这个问题,该字符串的格式是jquery自动完成可以更容易解析的。
然后在客户端:
I solved it by passing a string from the view side in the format that jquery autocomplete can parse easier.
Then on the client side: