2012-06-21 83 views
1

會對輸入自動完成,我這樣做: 在views.py自動完成返回不確定的數據

def getpositions(request): 
    if request.is_ajax(): 
     query = request.GET.get("term", "") 
     positions=Position.objects.filter(name__icontains=query) 
     results = [] 
     for position in positions: 
      position_json={} 
      position_json['name']=position.name 
      results.append(position_json) 
     data=simplejson.dumps(results) 
    else: 
     data = 'error' 
    return HttpResponse(data, mimetype='application/json') 

template

$(document).ready(function(){ 
        $("#positions").autocomplete({ 
         source: "{% url CompanyHub.views.getPositions%}", 
         success: function(data) { 
            response($.map(data, function(item) { 
             return { 
              label: item.name, 
              value: item.name 
             } 
            })); 
           }, 
         minLength: 2, 
         }); 
       }); 

#positions是:<input type="text" id="positions" />

每一件事是好的,但它只顯示Undefined,而不是顯示結果列表,我試過了許多事情,但沒辦法!

+2

您可以添加一個'debugger'指令和檢查什麼'data'包含 –

+2

您使用jQuery UI自動完成從這裏http://jqueryui.com/demos/autocomplete/是,那麼它不具有成功的選擇。 –

+0

克勞迪奧雷迪:我得到這個json的回覆:對象{name =「blah blah」} –

回答

0

jQuery UI自動完成沒有success選項用於格式化數據。檢查這裏的選項列表http://jqueryui.com/demos/autocomplete/。相反,您可以使用source選項的回調函數,並自己處理您自己的ajax調用,並根據需要格式化數據。

$("#positions").autocomplete({      
     source: function(req,resp) { 
     $.get("{% url CompanyHub.views.getPositions%}", 
       {term:req.term},function(data){ 
        resp($.map(data, function(item) { 
             return { 
              label: item.name, 
              value: item.name 
             }; 
            }) 
          ); 
          }); 
      }, 
      minLength: 2, 
      }); 
+0

是否正確?我得到錯誤,不知道是什麼問題! –

+0

@Asma,之前的括號中有問題,但我確定它現在應該正常工作。檢查並讓我知道。 –

+0

tnx一百萬但它有問題呢! –

相關問題