搜索框輸入搜索名字,從數據庫中篩選名字, 如果有包含輸入的字母的名字則以json格式返回並且顯示在搜索框下:
html文件:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta charset="utf-8"/> 6 <body> 7 <div style="margin-top: 300px;margin-left: 520px;"> 8 <form action="/Fsearch/" method="get" style="margin: auto 0;"> 9 請輸入英文名:<br/> 10 <input type="text" id="search-text" name="q"><button type="button" id='search-button'>搜索</button> 11 <p><span id='search-result'></span></p> 12 </form> 13 </div> 14 <script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> 15 <script> 16 $(document).ready(function(){ 17 $("#search-text").keyup(function(){ 18 var q = $("#search-text").val(); #獲取搜索框輸入的值 19 $.get("/Fsearch/",{'q':q}, function(data){ #參數:發送的url;傳入的數據;請求成功后的調用函數(data即是試圖函數返回的json格式數據)詳情 20 for (var i = data.length - 1; i >= 0; i--) { 21 $('#search-result').append(data[i]+'<br/>') #加入到search-result部分顯示 22 }; 23 }) 24 }); 25 $('#search-text').keydown(function(){ 26 $('#search-result').empty(); 27 }) 28 $('#search-text').blur(function(){ 29 $('#search-result').empty(); 30 }) 31 }); 32 </script> 33 </body> 34 </html>
對應的視圖函數:
1 def Fsearch(request): 2 q = request.GET['q'] 3 recontents = PreContent.objects.filter(name__contains=q) 4 5 #此地很重要,由於要返回json類型到模板,但是json.dumps()只能夠把python內置數據類型轉化為json,所以以下把上面
從數據庫中取出來的queryset型數據轉化為數組類型,再用json.dumps()方可成功。
6 rejson = [] 7 for recontent in recontents: 8 rejson.append(recontent.name) 9 return HttpResponse(json.dumps(rejson), content_type='application/json')