zoukankan      html  css  js  c++  java
  • flask后端、使用ajax、获取flask数据、传值到前端页面、如果数据存在显示标签、如果不存在不显示标签

    -------------------------------------第一部分-----------------------------------------------------------------------------------

    #主要app

    from flask import Flask,render_template
    import config
    from exts import db
    from models import User,Article,Tag
    #导入蓝图
    from articleview import article_bp



    app = Flask(__name__)
    app.config.from_object(config)

    #注册蓝图
    app.register_blueprint(article_bp)
    db.init_app(app)

    @app.route('/')
    def hello_world():
    #插入用户名
    user = User(username='zhiliao',email='xxx@qq.com')
    #插入文章
    article = Article(title='abc',content='123')

    #abc这个文章是zhiliao写的
    article.author = user

    tag1 = Tag(name='前端')
    tag2 = Tag(name='Python')

    #abc这个文章的标签有 前端、和Python
    article.tags.append(tag1)
    article.tags.append(tag2)

    #只需要添加article 那么和article相关联的所有对象就会被统一添加
    db.session.add(article)

    #提交
    db.session.commit()
    return render_template("index.html")


    if __name__ == '__main__':
    app.run(debug=True,port = 9999)

    -------------------------------------------第二部分、蓝图中使用 flask-restful发送是数据库数据、json数据的格式--------------------------------------------------------------------

    from flask import Blueprint,make_response,render_template,make_response
    from flask_restful import Resource,fields,marshal_with,Api
    from models import Article
    '''
    使用ajax给前端进行传值

    '''
    #使用蓝图
    article_bp = Blueprint("article",__name__,url_prefix="/article")

    #使用蓝图初始化app
    api = Api(article_bp)

    #当访问 article/list的时候要判断返回什么数据,是什么类型? 如果是get请求给他返回html,
    # @api.representation("text/html")
    # def output_html(data,code,headers):
    #
    # '''
    # 在这个函数里面判断 是什么数据? json 还是 html
    # :param data:
    # :param code:
    # :param headers:
    # :return: 在representation装饰的函数中, 必须返回一个Response对象
    # '''
    # # print(data)
    # print("data什么类型:",type(data))
    # if type(data) == str:
    # resp = make_response(data)
    # return resp
    # else:
    # # return data
    # pass


    class ArticleView(Resource):
    #验证要传递的数据
    resource_fields = {
    # attribute 的意思是修改名称 把title修改成school
    "school": fields.String(attribute="title"),
    "content":fields.String,
    # "author":fields.String,
    "author":fields.Nested({
    "username":fields.String,
    "email":fields.String
    }),
    # "tags":fields.String 需要传递列表
    "tags":fields.List(fields.Nested({
    "id":fields.Integer,
    "name":fields.String
    })),

    # default 指定是80
    "read_count":fields.Integer(default=80)
    }

    #
    @marshal_with(resource_fields)
    def get(self,article_id):
    #拿数据
    article = Article.query.get(article_id)
    #传递数据
    print("----------",article)
    return article

    api.add_resource(ArticleView,"/<article_id>/",endpoint = "article")




    class ListView(Resource):


    def get(self):

    #继承了 Resource的 视图,默认返回json数据,这里返回html 所以要用到11-29行代码
    return render_template("index.html")
    # return{"username":"wakaka"}
    api.add_resource(ListView,"/list/",endpoint = "list")





    ------------------------------------------------第三部分、前端页面如果数据存在 打印一个标签-------------------------------------------------------------

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>

    {# 引入 script#}
    <script src="../static/jq/jquery-2.1.0.js"></script>

    <script>

    $(function(){
    $.ajax({
    type: "get",

    {# 数据来自于 17 行#}
    url: "article/1/",
    data: {

    },

    {#格式#}
    dataType: "json",
    success: function(data){

    {#判断字典里面这个值是否存在,如果存在生成一个标签#}
    var sc= data.school;
    if(sc!=null&&sc!=''){
    var html = '<span>'+sc+'</span>';
    $("#bo").html(html);
    }








    {#简单的传参1、---------------------------------------------------------------#}
    {#控制台打印#}
    console.log(data.author.email);
    {#html页面显示#}
    $("#span1").html(data.author.email);

    var aa = "<tr><td>xxxxxxxxx</td><td>qqqqqq</td></tr>";

    {##给 id = #d1进行传递数据#}
    $("#id1").html(data.read_count);
    $("#id2").html(data.author.username);

    $("#tab").html(aa);
    }
    });
    });



    </script>
    </head>
    <body>
    {#<p>我是从模板当中渲染的</p>#}
    {#<span id="span1">这是现实邮箱的</span>#}
    {##}
    {#<p id = "id1"></p>#}
    {##}
    {#<span>这是通过jquery渲染数据</span><p id = "id2"></p>#}
    {##}
    {#<table id="tab" border="1" cellpadding="0" cellspacing="0"></table>#}
    <hr>

    <p id="bo"></p>
    </body>
    </html>
  • 相关阅读:
    zookeeper.KeeperException$UnimplementedException: KeeperErrorCode = Unimplemented for {root.path}
    IDEA对新建java线程池的建议
    Hbase配置WEB UI界面
    Tomcat清理日志文件无法立即释放磁盘空间
    Tomcat多应用启动报错:org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading Illegal access: this web application instance has been stopped already. Could not load [].
    Soliworks 2016建模细节总结(1)
    关于自学C语言开始时应该注意的问题分享—未完待续......
    Word或者WPS里证件照的背景底色和像素调整
    Linux命令大全(非常全,史上最全)
    Android项目结构介绍
  • 原文地址:https://www.cnblogs.com/yuanjia8888/p/13344252.html
Copyright © 2011-2022 走看看