AJAX实现省级城市二级联动

py文件

from flask import Flask, render_template, request
import json

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/ajaxDB'
# 指定不需要信号追踪
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 指定程序的启动模式为调试模式
app.config['DEBUG'] = True
# 指定执行完增删改之后的自动提交
# app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# 创建SQLalchemy的实例
db = SQLAlchemy(app)

class Province(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    pname = db.Column(db.String(30),unique=True,nullable=False)
    citys = db.relationship(
        "City",
        backref = "province",
        lazy = "dynamic"
    )
    def to_dic(self):
        dic = {"id":self.id,"pname":self.pname}
        return dic

class City(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    cname = db.Column(db.String(30))
    pid = db.Column(db.Integer,db.ForeignKey('province.id'))

    def to_dic(self):
        dic = {"id":self.id,"cname":self.cname,"pid":self.pid}
        return dic

@app.route("/09-work")
def work():
    return render_template("09-work.html")

@app.route("/09-server")
def server09():
    provinces = Province.query.all()
    list = []
    for pro in provinces:
        list.append(pro.to_dic())
    return json.dumps(list)

@app.route("/10-city")
def get_city():
    # 接收前端传递过来的PID的值,表示要查询的城市
    pid = request.args["pid"]
    cities = City.query.filter_by(pid=pid).all()
    list = []
    for c in cities:
        list.append(c.to_dic())
    return json.dumps(list)


if __name__ == '__main__':
    app.run(debug=True)
    db.create_all()

09-work.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery-1.11.3.js"></script>
    <script>
        function getProvince() {
            $.ajax({
                url:"/09-server",
                type:"get",
                async:false,
                dataType:"json",
                success:function (data) {
                    var html = "";
                    for (var i=0;i<data.length;i++) {
                        html += "<option value='"+data[i].id+"'>";
                        html += data[i].pname;
                        html += "</option>"



                    }
                    $("#prov").html(html);
                }
            })

        }

        function getCity(pid) {
            $.ajax({
                url:"/10-city",
                type: "get",
                async: true,
                data:"pid="+pid,
                dataType: "json",
                success:function (data) {
                    var html = "";
                    for (var i=0;i<data.length;i++) {
                        html += "<option value='"+data[i].id+"'>";
                        html += data[i].cname;
                        html += "</option>";
                    }
                    $("#citys").html(html)
                }
            })
        }

        $(function () {
            getProvince();
            {#网页加载时根据默认选中的省份取加载对应的城市#}
            getCity($("#prov").val());
            {#为prov绑定change事件#}
            $("#prov").change(function () {
                getCity(this.value)
            })
        })
    </script>
</head>
<body>

    省份:<select id="prov">
    </select>

    城市:<select id="citys">
    </select>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值