简体   繁体   中英

jQuery autocomplete function not working

I am using django for my project. Here is the view that I have created to get suggestions for a query:

def query_suggestions(request):
 if request.GET.has_key('term'):
   cols = Col.objects.filter(name__istartswith = request.GET['term'])[:3]
   fes = Fe.objects.filter(name__istartswith=request.GET['term'])[:3]
   users = User.objects.filter(first_name__istartswith=request.GET['term'])[:3]
   json_str = ""
   if users:
    json_str = json.dumps([{'label': user.first_name, 'value': '/'+ user.username + '/'} for user in users])
   if cols:
     json_str += json.dumps([{'label': col.name, 'value': col.get_absolute_url()} for col in cols])
   if fes:
     json_str += json.dumps([{'label': fe.name, 'value': fe.get_absolute_url()} for fe in fes])
   return HttpResponse(json_str)
 return HttpResponse()

This the script using jQuery for autocompletion:

$("#header-search-input").autocomplete({
      source: "/query_suggestions/",
      focus: function (event, ui) {
        $(event.target).val(ui.item.label);
        return false;
      },
      select: function (event, ui) {
        $(event.target).val(ui.item.label);
        window.location = ui.item.value;
        return false;
      }
    });

So, an input value m returns the HttpResponse() of [{"value": "/moni/", "label": "Moni"}, {"value": "/manisha/", "label": "Manisha"}][{"value": "/col/mira/", "label": "Mira"}]

BUt, this doesn't show the autocompletion suggestion under the search-input-bar . But, if I input mo it gives back [{"value": "/moni/", "label": "Moni"}] along with the suggestion under search-input-bar . What's the reason for this?

The code does not produce valid JSON, as you can see from your example: there is no comma between the lists.

You don't want to produce JSON by concatenating strings. Instead, build up lists or dicts in Python, then dump to JSON at the end:

data = []
if users:
  data.append([{'label': user.first_name, 'value': '/'+ user.username + '/'} for user in users])
if cols:
  data.append([{'label': col.name, 'value': col.get_absolute_url()} for col in cols])
if fes:
  data.append([{'label': fe.name, 'value': fe.get_absolute_url()} for fe in fes])
json_str = json.dumps(data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM