標籤:改進 setting names ima 載入 省市區 from on() 字典
使用Ajax
- 使用視圖通過上下文向模板中傳遞資料,需要先載入完成模板的靜態頁面,再執行模型代碼,產生最張的html,返回給瀏覽器,這個過程將頁面與Data Integration到了一起,擴充性差
- 改進方案:通過ajax的方式擷取資料,通過dom操作將資料呈現到介面上
- 推薦使用架構的ajax相關方法,不要使用XMLHttpRequest對象,因為操作麻煩且不容易查錯
- jquery架構中提供了$.ajax、$.get、$.post方法,用於進行非同步互動
- 由於csrf的約束,推薦使用$.get
- 樣本:實現省市區的選擇
- 最終實現效果
引入js檔案
修改settings.py關於靜態檔案的設定
STATIC_URL = ‘/static/‘STATICFILES_DIRS = [ os.path.join(BASE_DIR, ‘static‘),]
在models.py中定義模型
class AreaInfo(models.Model): aid = models.IntegerField(primary_key=True) atitle = models.CharField(max_length=20) aPArea = models.ForeignKey(‘AreaInfo‘, null=True)
產生遷移
python manage.py makemigrationspython manage.py migrate
通過workbench向表中填充樣本資料
在views.py中編寫視圖
- index用於展示頁面
- getArea1用於返回省級資料
- getArea2用於根據省、市編號返回市、區資訊,格式都為字典對象
from django.shortcuts import renderfrom django.http import JsonResponsefrom models import AreaInfodef index(request): return render(request, ‘ct1/index.html‘)def getArea1(request): list = AreaInfo.objects.filter(aPArea__isnull=True) list2 = [] for a in list: list2.append([a.aid, a.atitle]) return JsonResponse({‘data‘: list2})def getArea2(request, pid): list = AreaInfo.objects.filter(aPArea_id=pid) list2 = [] for a in list: list2.append({‘id‘: a.aid, ‘title‘: a.atitle}) return JsonResponse({‘data‘: list2})
在urls.py中配置urlconf
from django.conf.urls import urlfrom . import viewsurlpatterns = [ url(r‘^$‘, views.index), url(r‘^area1/$‘, views.getArea1), url(r‘^([0-9]+)/$‘, views.getArea2),]
主urls.py中包含此應用的url
from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [ url(r‘^‘, include(‘ct1.urls‘, namespace=‘ct1‘)), url(r‘^admin/‘, include(admin.site.urls)),]
定義模板index.html
- 修改settings.py的TEMPLATES項,設定DIRS值
‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],
- 定義模板檔案:包含三個select標籤,分別存放省市區的資訊
<!DOCTYPE html><html><head> <title>省市區列表</title></head><body><select id="pro"> <option value="">請選擇省</option></select><select id="city"> <option value="">請選擇市</option></select><select id="dis"> <option value="">請選擇區縣</option></select></body></html>
在模板中引入jquery檔案
<script type="text/javascript" src="static/ct1/js/jquery-1.12.4.min.js"></script>
編寫js代碼
- 綁定change事件
- 發出非同步請求
- 使用dom添加元素
<script type="text/javascript"> $(function(){ $.get(‘area1/‘,function(dic) { pro=$(‘#pro‘) $.each(dic.data,function(index,item){ pro.append(‘<option value=‘+item[0]+‘>‘+item[1]+‘</option>‘); }) }); $(‘#pro‘).change(function(){ $.post($(this).val()+‘/‘,function(dic){ city=$(‘#city‘); city.empty().append(‘<option value="">請選擇市</option>‘); $.each(dic.data,function(index,item){ city.append(‘<option value=‘+item.id+‘>‘+item.title+‘</option>‘); }) }); }); $(‘#city‘).change(function(){ $.post($(this).val()+‘/‘,function(dic){ dis=$(‘#dis‘); dis.empty().append(‘<option value="">請選擇區縣</option>‘); $.each(dic.data,function(index,item){ dis.append(‘<option value=‘+item.id+‘>‘+item.title+‘</option>‘); }) }) }); }); </script>
django之使用jquery完成ajax