django之使用jquery完成ajax

來源:互聯網
上載者:User

標籤:改進   setting   names   ima   載入   省市區   from   on()   字典   

使用Ajax
  • 使用視圖通過上下文向模板中傳遞資料,需要先載入完成模板的靜態頁面,再執行模型代碼,產生最張的html,返回給瀏覽器,這個過程將頁面與Data Integration到了一起,擴充性差
  • 改進方案:通過ajax的方式擷取資料,通過dom操作將資料呈現到介面上
  • 推薦使用架構的ajax相關方法,不要使用XMLHttpRequest對象,因為操作麻煩且不容易查錯
  • jquery架構中提供了$.ajax、$.get、$.post方法,用於進行非同步互動
  • 由於csrf的約束,推薦使用$.get
  • 樣本:實現省市區的選擇
  • 最終實現效果

引入js檔案
  • 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向表中填充樣本資料
  • 參見“省市區.sql”
  • 注意將表的名稱完成替換
在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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.