Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

python - Django, jQuery, and autocomplete

After some extensive research (Googling), I cannot find a current tutorial on how to set up autocomplete using Django and jQuery. There appears to be a variety of plugins and there appears to be no consistency or standard about which to use or when.

I'm not a pro at either Django or jQuery, but need an autocomplete solution that is well documented and fairly simple to utilize.

Suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're looking to search from within your django models then something like:

from django.utils import simplejson
    def autocompleteModel(request):
    search_qs = ModelName.objects.filter(name__startswith=request.REQUEST['search'])
    results = []
    for r in search_qs:
        results.append(r.name)
    resp = request.REQUEST['callback'] + '(' + simplejson.dumps(result) + ');'
    return HttpResponse(resp, content_type='application/json')

For the jQuery autocomplete and call:

function searchOpen() {
    var search = $('#txtSearch').val()
    var data = {
        search: search
    };
    $.ajax({
        url: '/search.json',
        data: data,
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'searchResult'
    });
}


function searchResult(data) {
    $( "#txtSearch" ).autocomplete ({
        source: data
    });
}

Finally to connect it all on your input form would have something like:

<input type="text" name="search" id="txtSearch" onkeyup="searchOpen()" />

Note, this is using Jquery UI as well in addition to stock jQuery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...