2017-06-16 71 views
2

重用jQuery的自動完成:https://jqueryui.com/autocomplete/#remotejQuery的自動完成Python和webapp2的

我類似的方式工作,要求遠程數據源:這是我的代碼

class Products(webapp2.RequestHandler): 
    def get(self): 
     self.response.headers['Content-Type'] = 'application/json' 
     data = ['cat','dog','bird', 'wolf'] 
     data = json.dumps(data) 
     self.response.out.write(data) 

app = webapp2.WSGIApplication([ 
    ('/', MainPage), 
    ('/products', Products), 
], debug=True) 

和JS

<script> 
    $("#autocomplete").autocomplete({ 
     minLength: 2, 
     source: "/products" 
    }); 
</script> 

我有自動完成似乎與2最低typeaheads工作。但是在測試時,它不會自動完成/正確搜索。即。無論我搜索什麼,它都會查詢列表中的所有4個項目。當您使用的URL源

回答

1

Jquery的不過濾列表。它在查詢字符串中傳遞搜索詞作爲術語變量。爲遠程源的文檔是在這裏:http://api.jqueryui.com/autocomplete/#option-source

您需要根據項請求參數在你的處理器返回過濾後的數據。換句話說,改變了你的產品的處理程序,以更多的東西是這樣的:

class Products(webapp2.RequestHandler): 
    def get(self): 
     term = self.request.get('term', None) 
     self.response.headers['Content-Type'] = 'application/json' 
     data = ['cat', 'dog', 'bird', 'wolf'] 
     if term: 
      data = [i for i in data if i.find(term) >= 0 ] 
     data = json.dumps(data) 
     self.response.out.write(data) 

下面是一個基於jQuery開發的UI自動完成樣本的完整工作示例:

import webapp2 
import json 

class MainPage(webapp2.RequestHandler): 
    def get(self): 
     self.response.out.write(""" 
<html> 
<head> 
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> 
<script> 
    $(function() { 
    function log(message) { 
     $("<div>").text(message).prependTo("#log"); 
     $("#log").scrollTop(0); 
    } 

    $("#animals").autocomplete({ 
     source: "./products", 
     minLength: 2, 
     select: function(event, ui) { 
     log("Selected: " + ui.item.value + " aka " + ui.item.id ); 
     } 
    }); 
    }); 
</script> 
</head> 
<body> 
<div class="ui-widget"> 
    <label for="animals">Animals: </label> 
    <input id="animals"> 
</div> 

<div class="ui-widget" style="margin-top:2em; font-family:Arial"> 
    Result: 
    <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div> 
</div> 
</body> 
</html> 
""") 

class Products(webapp2.RequestHandler): 
    def get(self): 
     term = self.request.get('term', None) 
     self.response.headers['Content-Type'] = 'application/json' 
     data = ['cat', 'dog', 'bird', 'wolf'] 
     if term: 
      data = [{"label":i, "id":i + "_id"} for i in data if i.find(term) >= 0 ] 
     data = json.dumps(data) 
     self.response.out.write(data) 

app = webapp2.WSGIApplication([ 
    ('/', MainPage), 
    ('/products', Products), 
], debug=True) 

def main(): 
    from paste import httpserver 
    httpserver.serve(app, host="0.0.0.0", port="8080") 

if __name__ == '__main__': 
    main()