jQueryUI autocomplete with url as source (am using Django)

梦想与她 提交于 2019-12-21 17:48:46

问题


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 url 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)


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5020844/jqueryui-autocomplete-with-url-as-source-am-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!