This time I will bring you the use of jquery and ajax for data interaction. What are the precautions for using jquery and ajax for data interaction? The following is a practical case, let's take a look.
The jquery framework provides $.ajax, $.get, and $.post methods for asynchronous interaction. Since Django uses CSRF constraints by default, it is recommended to use $.get Example: Implement province and city selection Copy the jquery file to thestatic/js/ directory
Open the booktest/views.py file and defineview area1, used to display drop-down list
#提供显示下拉列表的控件,供用户操作 def area1(request): return render(request,'booktest/area1.html')
url('^area1/$',views.area1),
nbsp;html> <meta> <title>Title</title> <script></script> <script> $(function () { $.get('/sheng/',function (data) {//{slist:[]} var slist=data.slist;//[{},{},{}...] var sheng=$('#sheng'); $.each(slist,function (i,n) { //n==>{id:,title:} sheng.append('<option value="'+n.id+'">'+n.title+'') }); }); $('#sheng').change(function () { var sid=$(this).val(); if(sid!='0'){ $.get('/shi/',{'sid':sid},function (data) { var slist=data.slist; var shi=$('#shi').empty().append('<option value="0">请选择'); $('#qu').empty().append('<option value="0">请选择'); $.each(slist,function (i,n) { shi.append('<option value="'+n.id+'">'+n.title+''); }); }); } }); $('#shi').change(function () { var sid=$(this).val(); if(sid!='0'){ $.get('/shi/',{'sid':sid},function (data) { var slist=data.slist; var shi=$('#qu').empty().append('<option value="0">请选择'); $.each(slist,function (i,n) { shi.append('<option value="'+n.id+'">'+n.title+''); }); }); } }); }); </script> <select> <option>请选择</option> </select> <select> <option>请选择</option> </select> <select> <option>请选择</option> </select>
url('^sheng/$',views.sheng),
from django.http import JsonResponse def sheng(request): slist=AreaInfo.objects.filter(aParentisnull=True) ''' [{id:,title:},{},{}] ''' slist2=[] for s in slist: slist2.append({'id':s.id,'title':s.atitle}) return JsonResponse({'slist':slist2})
url('^sheng/$',views.sheng),
http://127.0.0.1:8000/sheng/
#根据pid查询子级区域信息 def shi(request): sid=request.GET.get('sid') slist=AreaInfo.objects.filter(aParent_id=sid) slist2=[] for s in slist: slist2.append({'id':s.id,'title':s.atitle}) return JsonResponse({'slist':slist2})
url('^shi/$',views.shi),
http://127.0.0.1:8000/shi/?sid=140000/
Enter the following URL in the browser http://127.0.0.1:8000/shi/ I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:The above is the detailed content of Using jquery and ajax for data interaction. For more information, please follow other related articles on the PHP Chinese website!