# ajax
* 使用視圖通過上下文向模板中傳遞數據,需要先加載完成模板的靜態頁面,再執行模型代碼,生成最張的html,返回給瀏覽器,這個過程將頁面與數據集成到了一起,擴展性差
* 改進方案:通過ajax的方式獲取數據,通過dom操作將數據呈現到界面上
* 推薦使用框架的ajax相關方法,不要使用XMLHttpRequest對象,因為操作麻煩且不容易查錯
* jquery框架中提供了$.ajax、$.get、$.post方法,用于進行異步交互
* 由于csrf的約束,推薦使用$.get
* 示例:實現省市區的選擇
* 最終實現效果如圖:

## 引入js文件 {#引入js文件}
* js文件屬于靜態文件,創建目錄結構如圖:

## 修改settings.py關于靜態文件的設置 {#修改settingspy關于靜態文件的設置}
```text
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
```
## 在models.py中定義模型 {#在modelspy中定義模型}
```text
class AreaInfo(models.Model):
aid = models.IntegerField(primary_key=True)
atitle = models.CharField(max_length=20)
aPArea = models.ForeignKey('AreaInfo', null=True)
```
## 生成遷移 {#生成遷移}
```text
python manage.py makemigrations
python manage.py migrate
```
## 通過workbench向表中填充示例數據 {#通過workbench向表中填充示例數據}
* 注意將表的名稱完成替換
## 在views.py中編寫視圖 {#在viewspy中編寫視圖}
* index用于展示頁面
* getArea1用于返回省級數據
* getArea2用于根據省、市編號返回市、區信息,格式都為字典對象
```text
from django.shortcuts import render
from django.http import JsonResponse
from models import AreaInfo
def 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 {#在urlspy中配置urlconf}
```text
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^area1/$', views.getArea1),
url(r'^([0-9]+)/$', views.getArea2),
]
```
## 主urls.py中包含此應用的url {#主urlspy中包含此應用的url}
```text
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^', include('ct1.urls', namespace='ct1')),
url(r'^admin/', include(admin.site.urls)),
]
```
## 定義模板index.html {#定義模板indexhtml}
* 修改settings.py的TEMPLATES項,設置DIRS值
```text
'DIRS': [os.path.join(BASE_DIR, 'templates')],
```
* 定義模板文件:包含三個select標簽,分別存放省市區的信息
```text
<!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文件 {#在模板中引入jquery文件}
```text
<script type="text/javascript" src="static/ct1/js/jquery-1.12.4.min.js"></script>
```
## 編寫js代碼 {#編寫js代碼}
* 綁定change事件
* 發出異步請求
* 使用dom添加元素
```text
<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>
```