嗨,我创建自动完整的seacrh
javascript
jQuery(function() {
$("#id_input").on('keyup', function(){
var value = $(this).val();
$.ajax({
url: "{% url 'ajax_autocomplete' %}",
data: {
'search': value
},
dataType: 'json',
success: function (data) {
list = data.list;
$("#id_input").autocomplete({
source: list,
minLength: 3
});
}
});
});
});
查看:
def autocomplete_search(request):
if request.is_ajax():
game = None
try:
game = Game.objects.get(name=request.GET.get('search', None))
except:
pass
if game is not None:
result = redirect('games')
else:
queryset = Game.objects.filter(name__startswith=request.GET.get('search', None))
list = []
for i in queryset:
list.append(i.name)
data = {
'list': list,
}
result = JsonResponse(data)
return result
,但是当game is not None
它只是响应页面时,它并没有重定向。但是我想在game != None
并加载所需的页面时停止请求。怎么了?
是因为您将重定向函数分配到变量中,因此它无法正常工作。您只需要在条件的两端返回。
尝试这样的事情:
def autocomplete_search(request):
if request.is_ajax():
game = None
try:
game = Game.objects.get(name=request.GET.get('search', None))
except:
pass
if game is not None:
return redirect('games')
else:
queryset = Game.objects.filter(name__startswith=request.GET.get('search', None))
list = []
for i in queryset:
list.append(i.name)
data = {
'list': list,
}
return JsonResponse(data)
thx for karthikr 我下一步做到了
def autocomplete_search(request):
if request.is_ajax():
game = None
try:
game = Game.objects.get(name=request.GET.get('search', None))
except:
pass
if game is not None:
data = {
'redirect': '/link-to-redirect/'
}
result = redirect('games')
else:
queryset = Game.objects.filter(name__startswith=request.GET.get('search', None))
list = []
for i in queryset:
list.append(i.name)
data = {
'list': list,
}
result = JsonResponse(data)
return result
和jQuery更改下一步:
$.get({% url 'ajax_autocomplete' %}, {
data: $('#search-game').val()
}, function (response) {
if (response.redirect !== undefined) {
top.location.href=response.redirect;
} else {
list = response.list;
$("#search-game").autocomplete({
source: list,
minLength: 2
});
}
});