2013-11-25 100 views
0

建議,我有我的jQuery自動完成這樣的jQuery的汽車用Ajax和Django的

$(function(){ 
    $("#id_q").autocomplete({ 
     //source: availableTags, This works.....(static list are working) 
     source: function (request, response) { // This is not working 
      $.ajax ({ 
       url: '/college-search/autosuggest/', 
       data: { 'keyword':$('#id_q').val(), 'page' = 'searchbox'}, 
       dataType: "json", 
       type: "POST", 
       contentType: "application/json; charset = utf-8", 
       success: function (data) { 
        response (data.autosuggest); 
       }, 
       error: function (XMLHttpRequest, textStatus, errorThrown) { 
       } 

      }); 
     }, 
    minLength: 1, 
    //open: function() { $(this).autocomplete("widget").css({"width": $(this).width()+6})}, 
    //appendTo:$(".cls_comp").parent(), 
    select: function(event, ui) { } 

    }); 
} 

和我的Django的看法是這樣 -

def auto_suggest(request): 

    autosuggest = [] 
    s_query = '' 
    spelling = '' 
    letters = '' 
    lenletters ='' 
    loc = '' 

    baseurl = settings.HAYSTACK_SOLR_URL 

    baseurl = baseurl + 'terms?terms.fl=autocomplete_text&omitHeader=true&terms.limit=5000&terms.sort=index&wt=json&terms.prefix=' 
    if request.GET.has_key('keyword'): 
     letters = request.GET.get('keyword') 
     letters = letters.lower() 
     letters = letters.replace(' ', '+') 
     lenletters = len(letters) 
    print "==================="  

    targeturl = baseurl + letters 

    print targeturl 

    if letters != '': 
     resp = requests.get(targeturl) 
     text = resp.text.encode('utf-8') 
     jsontext = json.loads(text) 
     autosuggest =[x for x in jsontext['terms']['autocomplete_text'] if x!= 1] 

    print autosuggest 

    if request.GET.has_key('page'): 
     webpage = request.GET.get('page') 
     if webpage == 'searchbox': 
      template = 'widgets/searchbox.html' 
     elif webpage == 'searchboxlong': 
      template = 'widgets/searchbox_long.html' 
     else: 
      template = '' 

    if request.GET.has_key('spellcheck'): 
     misspelled_word = request.GET.get('spellcheck') 
     s_query = misspelled_word 
     spelling = spell_check(misspelled_word) 

    context = { 
    'autosuggest' : autosuggest, 
    'lenletters' : lenletters, 
    'letters' : letters, 
    'searches' : searches, 
    'spelling' : spelling, 
    'loc' : loc, 
    } 
    return render_to_response(
     template,context, context_instance=RequestContext(request) 
    ) 

我的問題是我不能夠做一個ajax當我在ID = id_q的文本框中輸入內容時請致電。

無法理解我在做什麼錯..... 任何幫助將十分讚賞

+0

在調試控制檯中是否有任何錯誤? – mariodev

+0

在調試控制檯中什麼都沒有發生......我想自動完成功能並沒有調用 –

回答

1

你有一個語法錯誤的位置:

data: { 'keyword':$('#id_q').val(), 'page' = 'searchbox'}, 

應該

data: { 'keyword':$('#id_q').val(), 'page': 'searchbox'}, 

而這是沒有意義的:

response (data.autosuggest) 

你在那裏做什麼?你的意思是return data.autosuggest

另外,你可能不想爲Django響應渲染模板 - 它應該只是JSON。你至少應該發佈'widgets/searchbox.html'的內容。

+0

謝謝...它像一個魅力 –