jquery ajax
1. 导入jquery文件。
STATICFILES_DIRS=( os.path.join(BASE_DIR,'static'), )
2.创建url:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 urlpatterns = [ 2 path('admin/', admin.site.urls), 3 path(r'search/',views.search), 4 ]
3.创建视图:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def search(req): if req.method=='POST': username=req.POST.get("username") or '' dic={"flag":False} if username=='zhoujielun': # dic['flag']=True # dic['flag']=Testdb.objects.values_list("ip") va=Testdb.objects.values("ip") result=[] for i in va: result.append(i['ip']) dic['flag']='\n'.join(result) return HttpResponse(json.dumps(dic)) else: return render(req,'search.html')
4.创建模板文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 {% load staticfiles %} 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>search</title> 7 <script src="{% static 'jquery-3.2.1.js' %}"></script> 8 </head> 9 <body> 10 <input type="text" class="search-label-icon" id="search"/> 11 <form> 12 {% csrf_token %} 13 <input type="submit" class="btn-danger"> 14 </form> 15 <div><span id="va"></span></div> 16 <script> 17 $("#search").keyup(function () { 18 $.ajax({ 19 url:'/search/', 20 type:"POST", 21 data:{ 22 "username":$(this).val(), 23 "csrfmiddlewaretoken":"{{ csrf_token }}", 24 }, 25 success:function (a) { 26 var newstr=JSON.parse(a); 27 if (newstr["flag"]) { 28 $span=$("<span>"); 29 $span.text(newstr["flag"]) 30 $("#search").after($span) 31 } 32 } 33 }) 34 } 35 ) 36 </script> 37 </body> 38 </html>
posted on 2018-06-20 23:43 mingxiazhichan 阅读(124) 评论(0) 编辑 收藏 举报