Django实现Ajax请求城市列表

一、需求: 实现如下图的区域显示选择功能

这里写图片描述

二、思路分析

(一)显示省份

配置url: http://127.0.0.1:8000/show_areas
定义视图:

def show_areas(request):
# 查询所有的省份数据
pass
定义模板: show_areas.html, 使用模板语言显示省份

(二)切换省份,显示城市

后台实现

配置url: http://127.0.0.1:8000/get_children/上级区域id
视图函数:

def get_children(request, parent_id):
“”“获取下级区域数据”“”
# …
return JsonResponse(‘…’)
测试视图逻辑是否正确

在浏览器中访问地址,例如:http://127.0.0.1:8000/get_children/20,确认视图是否返回了正确的json城市数据; (提示:id为20表示广东省)

扫描二维码关注公众号,回复: 387809 查看本文章

前端实现

配置静态文件(css, js, image )

在项目下创建static/js目录,复制jquery到static/js目录下.
在项目下的setting.py文件中配置:

指定静态文件所在的物理目录
STATICFILES_DIRS = [os.path.join(BASE_DIR, ‘static’)]
前端js代码编写

监听省份的改变

// change: 监听select标签的选中事件
(‘#province’).change(function () {      var id = (this).val(); // 选中的区域id
alert(id);
})
发起ajax get请求获取城市数据,并刷新界面显示

$.get(‘url请求地址’, function(result) {
// result服务器返回的数据
})
(三)切换城市显示区县

与 切换省份显示城市 类似

(四)juery函数

$.each()

json数据:

{
“children”: [
[232, “广州市”],
[233, “韶关市”],
[234, “深圳市”]
]
}
遍历:

$.each(data.children, function(index, area){ // index: 第几次循环
var id = area[0]; // 区域id
var title = area[1]; // 区域名称
console.log(index, id, title) // 输出信息
})
data代表上述的json数据
data.children 为数组
输出结果

0 232 广州市
1 233 韶关市
2 234 深圳市

引入js文件

js文件属于静态文件,创建目录结构如图:
static
这里写图片描述
修改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 makemigrations
python manage.py migrate

通过workbench向表中填充示例数据
参见“省市区.sql”
注意将表的名称完成替换
在views.py中编写视图
index用于展示页面
getArea1用于返回省级数据
getArea2用于根据省、市编号返回市、区信息,格式都为字典对象

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

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

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
在项目中的目录结构如图:
templates
这里写图片描述
修改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>

SQL文件:
数据库被我删了…..自重

猜你喜欢

转载自blog.csdn.net/chenhua1125/article/details/80113526