jQuery for the reception, Python3-Flask for the back end of a full stack development - data interactively

Long time no blog some friends! No, 2019 is the year of Dream! We must redouble our efforts!

Chinese New Year at home, alone to complete the development of large database operations, the theme is "artisan tutorials to share with the finished product to sell online," online mall, project code, see: craftsmen hall , an assembly of:

1. written tutorial (picture + text);

2. Comments;

3. Like feature points;

4. online transactions (of course it is a virtual currency);

5. Tutorial search function;

6. Application of the salt value based on the user password (password) stored in a protective manner.

On for a Home shots.

 Well, the following entry to the topic - how to how to achieve data exchange between the front and back of jQuery and flask!

A reasonable definition of engineering structures 

See in particular my previous blog: https://blog.csdn.net/WinerChopin/article/details/81053626

It is worth noting: When we use the framework of the flask, there are two folders are necessary, namely static and Templates ,

Of these, only placed in static pictures and resources can be in the foreground JS or jQuery code to access in order to achieve dynamic update, it is important! ; Only the templates in HTML pages can be flask to return after a search, rendering!

Second, the front and back of the data exchange

2.1 returns the HTML page rendering 

1. frontend user access to the specified URL, background make_response returns the corresponding HTML page

首先我们完成一个简单demo,

# main.py
from flask import Flask, request, render_template, make_response, redirect, url_for
import simplejson

app = Flask(__name__)
# 新建一个应用

@app.route('/test')
# 设置路由我们如果想要访问这个函数,就需要输入路由:[ip地址]/test
def index():
    response = make_response(render_template('index.html'))
    # 定义一个返回的对象
    '''
    注意,在flask中每个涉及到URL访问的函数必须返回值,返回值有以下三种——
        1)返回flask定义的对HTML页面的操作,如:渲染页面,重定向指定网页;
        2)返回字符串,注意,不能返回True或False!!!
        3)返回simplejson的字典(键值对),后面会讲,不着急!
    '''
    return response

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

当然实现定义好index.html如:,这时候运行,在浏览器输入:http://127.0.0.1:5000/test,就可以看到:啦!四不四很激动?!更厉害的还在后头呢!

2. 前台超链接<a/>标签直接链接指定HTML页面

1)在main.py文件中添加对应的路由即函数返回对应的content.html页面,一般的,我们倾向于让url的最后一级与函数名与对应的HTML文件的名字,这三者保持一致。

# ...............

@app.route('/test/content')
def content():
    response = make_response(render_template('content.html'))
    return response

# ...............

2)修改index.html文件,新增一个<a/>元素,如图:

3)新建content.html如图:

4)这时候按住ctrl+shift+R对index页进行刷新,得到:

点击超链接,可以跳转到:

2.2 用"$.ajax"提交数据,并获取后台通过simplejson返回的数据

 为了使用jQuery,首先,我们需要在项目中引入jQuery的.js文件。现在网络上有很多版本,我们可以有两个方式应用——

1. 下载jQuery.js文件放在"/static/js"目录下,然后引用;

2. 直接链接到jQuery.js文件的资源的超链接;

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h>这是首页!</h>
    <h1>前往<a href="{{url_for('content')}}">内容页</a></h1>
</body>

<!--javascript-->
<!-- 方式1 -->
<script type="text/javascript" src="../static/js/jquery-2.2.4.min.js"></script>
<!-- 方式2:引用官方地址 -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest,js"></script>
</html>

现在我们可以使用ajax了!

1)修改index.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <h>这是首页!</h>
    <h1>前往<a href="{{url_for('content')}}">内容页</a></h1>
    <input type="button" id="btn" value="点击按钮上传数据"/>
    <!--新添加一个按钮,设置 id 为 btn,等下我们要通过 id 访问它!-->
</body>

<!--javascript-->
<script type="text/javascript" src="../static/js/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
    <!--用jquery为制定 id 的元素添加点击触发事件-->
    $('#btn').on("click", function () {
        var data = {
            'signal': -1,
            'string': 'super me'
        };
        // 定义要发送的数据,是键值对!这里有两对,一个是整型,一个是字符串

        $.ajax({
            type:'GET',
            url:'/../test/response_1',
            data: data,
            dataType:'json',
            success: function (data) {
                if(data.state>=0){
                    // 对比下面后台返回数据的格式,相信你会很容易发现规律!!!
                    console.log(data.reply_signal);
                    console.log(data.reply_string);
                }
            },
            error: function(){
                console.log("failure!");
            }
            /*
            这里很重要,我们要设置:type, url, data, dataType, success, error 的值
            其中:
                1)type是指数据传输方式是GET(对应的还有POST)
                2)url是数据要提交到的目的路由,注意这里的格式"/../test/destination_name",这要与下面对后台设置的一个接收与返回数据的函数设置的路由格式向对应起来!
                3)data就是我们封装好了的要提交的数据
                4)dataType指定数据以什么格式传输,一般选择json格式
                5)success与error是两个函数,分别对应当数据提交并获取相应成功与失败后执行什么动作!其中,success的函数一般有一个参数data,用来表示从后台接收到的封装好的数据。
            */
        });
    })
</script>
</html>

然后,在main.py文件中添加新的响应函数——

# .......................
@app.route('/test/response_1', methods=['GET'])
# 注意路由的设置规律:/test/destination_name
def response_1():
    # 前面说到函数名最好与url最后一级相同,方便记忆
    
    # 下面这种格式是小编个人推荐的
    state = -1
    # state用来辅助判断后台是否准确收到了前台的数据
    signal = -1
    string = ''
    # 对要接收的数据进行声明;避免数据接收失败时,如果后面尝试使用它,就会出错!

    使用try结构,更加安全
    try:
        signal = int(request.args.get('signal', 0))    # 接收整型数据,但是,由于接受的数据格式仍是json即字符串,所以还需要作类型转换
        string = request.args.get('string', '')        # 接受字符串数据
        print(signal)
        print(string)
        # debug少不了的输出打印
        state += 1
    except:
        pass

    return simplejson.dumps({
        'state': state,
        'reply_signal': signal+1,
        'reply_string': string+', i do!'
    })
    # 后台返回数据也是采用键值对的形式!
    # 对比上面前台接受数据data后如何解析,你会很快发现规律!
# .......................

现在就准备好了!

刷新index页面,得到

 

按住F12检查,发现前台打印出了对应的接收到的数据——

 

并且,在后台,也将接收到的数据打印了出来——

2.3 submit提交form的数据,并重定向网页

1)在index.html的<body/>中添加表单<form/>

<body>
    ...
    <form method="post" action="/test/response_2" enctype="multipart/form-data">
        <input type="text" name="txt"/>
        <input type="submit" value="提交数据">
    </form>
    <!--
    这里的action指定了表单里数据要提交到的目的路由。
    当点击submit按钮时,表单里的所有值input的会被提交;
    其中,在后台我们会通过 name 去识别来自表单里的哪一个input的值!这一点很重要!
    -->
    ...
</body>

 2)在main.py新增响应函数response_2

# ...
@app.route('/test/response_2', methods=['post'])
# 表单的提交方式默认使用post
def response_2():
    state = -1
    txt = ''
    try:
        txt = request.form['txt']
        # 获取表单上名字为 txt 的组建的值(为字符串类型)
        print(txt)
        state += 1
    except:
        pass

    return redirect(url_for('content'))
    # 返回另一个网页,这里的content是指前面我们写的content函数,用来返回content.html并渲染

# ...

 3)查看效果,刷新index页面,得到

输入一些文本,点击提交,我们会发现:后台会获取到这些文本,并打印出来,

 

同时,前台会跳转到content页面!

 

好了,关于jQuery作前台,Python3-Flask作后端的3重数据交互方式就介绍到这里,后期小编遇到新的方式会持续更新;有任何疑惑欢迎评论区交流!本文有任何失误欢迎不吝指出!

 

 

 

 

 

Guess you like

Origin blog.csdn.net/WinerChopin/article/details/87886777