开发者

jQueryUI autocomplete with url as source (am using Django)

I am using Django web-framework for database, page generation etc.

jQueryUI / javascript side of the code

I want to use jQueryUI's autocomplete widget, as my data set will contain about 1,000 entries I wanted to query the database. On the link above it claims you can simply provide a url that returns JSON data:

Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:

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

I have taken the default example from the website, which works 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 functionality doesn't work at all.

I've tried making the url actually return an error (to see if it uses it) and putting in the full u开发者_StackOverflow中文版rl http://localhost:8000/search/, nothing works.

Django part of the 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 must be something wrong with my code and I would greatly appreciate any help you can offer :)


EDIT SOLUTION:

Thanks to @Thierry realised it didn't have a return statement before, have added that so I now looks like so:

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

And it actually works!

(It always seems to be the really small bugs that waste the most of of my time, grrr)


I return my ajax response like the following:

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. Once you see the output, the autocomplete should work.


There are some changes in json serialization API in later versions

  • 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜