from django.conf.urls import url
import views
urlpatterns = [
url(r'^area/$',views.area),
url(r'^area/(\d+)/$',views.area1),
url(r'^area/city(\d+)/$',views.area2),
url(r'^area/district(\d+)/$',views.area3)
]
#coding=utf-8
from django.shortcuts import render
from django.conf import settings
import os
from django.http import HttpResponse,JsonResponse
from django.core.paginator import Paginator
from models import *
# 省市区
def area(request):
return render(request,'booktest/area.html')
def area1(requset,id):
id1=int(id)
if id1==0:
data = AreaInfo.objects.filter(pid__isnull=True)
else:
data=[{}]
list=[]
for area in data:
list.append([area.id,area.title])
return JsonResponse({'data':list})
数据格式:{ [ [], [], [], [],[] ] }
def area2(request,id):
id1=int(id)
data = AreaInfo.objects.filter(pid_id=id1)
list=[]
for item in data:
list.append({'id':item.id,'title':item.title})
return JsonResponse({'data':list})
print (list)
# 数据格式 {'data':[{'id':1,'title':北京},{'id':2,'title':上海},{}。。。。。]}
def area3(request,id):
id1 = int(id)
data = AreaInfo.objects.filter(pid_id=id1)
list=[]
for item in data:
list.append({'id':item.id,'title':item.title})
return JsonResponse({'data':list})
print (list)
area.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>area</title>
<script src="/static/booktest/jquery-1.12.4.min.js"></script>
<script>
$(function () {
pro=$('#province')
city=$('#city')
district=$('#district')
$.get('/area/0/',function(dic){
$.each(dic.data,function (index,item) {
pro.append('<option value="'+item[0]+'">'+item[1]+'</option>')
})
})
pro.change(function () {
city.empty().append('<option value="" >请选择市</option>')
$.get('/area/city'+pro.val()+'/',function (list) {
$.each(list.data,function (index,item) {
city.append('<option value="'+item.id+'">'+item.title+'</option>')
})
})
})
city.change(function () {
district.empty().append('<option value="" >请选择区</option>')
$.get('/area/district'+city.val()+'/',function (list) {
$.each(list.data,function (index,item) {
district.append('<option value="'+item.id+'">'+item.title+'</option>')
})
})
})
});
</script>
</head>
<body>
<select id="province" style="background: deepskyblue">
<option value="" >请选择省</option>
</select>
<select id="city" style="background: yellow">
<option value="" >请选择市</option>
</select>
<select id="district" style="background: red">
<option value="" >请选择区</option>
</select>
</body>
</html>
使用mysql数据库:
结果: