JQueryUI autocomplete with url as source (I use Django)

I use the Django web framework to create a database, create pages, etc.

jQueryUI / side of JavaScript code

I want to use jQueryUI autocomplete widget , since my data set will contain about 1000 records that I wanted to query in the database. From the link above, he claims that you can simply provide a URL that returns JSON data:

Autocomplete can be configured to work with various data sources by simply specifying the source option. Data source can be:

* an Array with local data * a String, specifying a URL * a Callback 

I accepted the default example on a website that runs on my system.

However, if I change the following:

  $( "#tags" ).autocomplete({ source: availableTags, }); 

to

  $( "#tags" ).autocomplete({ source: "/search/", // url that provides JSON data }); 

the autocomplete function does not work at all.


I tried to make url really return an error (to make sure that it uses it) and insert the full url http://localhost:8000/search/ , nothing works.


Django piece of code

In url.py

 ... (r'^search/$', 'search'), ... 

In views.py

 from django.http import HttpRequest, HttpResponse from django.utils import simplejson ... def search(request): HttpResponse(simplejson.dumps(["hello", "world"])) # Will implement proper suggestions when it works. 



There should be something wrong in my code, and I would really appreciate any help you can offer :)


SOLUTION DECISIONS:

Thanks to @Thierry, I realized that there was no return before, they added that now I look like this:

 def search(request): output = ["hello", "world"] return HttpResponse(simplejson.dumps(output)) 

And it really works!

(These seem to be really small bugs that spend most of my time, grrr)

+4
source share
2 answers

I am returning my ajax response as follows:

 def search(request): output = ["hello", "world"] return HttpResponse(output, mimetype="application/javascript") 

If you access the URL http://localhost:8000/search/ , you should see the output. When you see the result, autocomplete should work.

+2
source

There are several changes in later versions in the json serialization API

  • For django 1.6 use

     import json from django.http import HttpResponse .... return HttpResponse(json.dumps(my_data_dictionary)) 
  • For django 1.7+ do it like here

+1
source

Source: https://habr.com/ru/post/1339494/


All Articles