首頁 > 軟體

Flask框架運用Ajax實現資料互動的範例程式碼

2022-11-09 14:01:49

使用Ajax技術網頁應用能夠快速地將增量更新呈現在使用者介面上,而不需要過載重新整理整個頁面,這使得程式能夠更快地迴應使用者的操作,如下筆記將簡單介紹使用AJAX如何實現前後端資料通訊。

前後端傳送字串

前端程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
	<script src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function SendAjax(){
            $.ajax({
                url:"/",
                contentType: "POST",
                data:{"head":"hello lyshark"},
                success:function(data){
                    if(data=="1"){
                        alert("請求已經提交.");
                    }
                },
                error:function(){
                     alert("執行失敗了...")
                }
            });
        }
    </script>
    <form action="/" method="post">
        <input type="button" value="傳送資料" onclick="SendAjax()">
    </form>
</body>
</html>

Flask後端程式碼

from flask import Flask,render_template,request
import json

app = Flask(import_name=__name__,
            static_url_path='/python',   # 設定靜態檔案的存取url字首
            static_folder='static',      # 設定靜態檔案的資料夾
            template_folder='templates') # 設定模板檔案的資料夾

@app.route('/', methods=["GET","POST"])
def index():
    if request.method == "POST":
        # 接收資料
        token = request.headers.get("Authorization")
        json_value = request.get_json()
        print(f"token = {token} username = {json_value['username']} password = {json_value['password']}")

        # 傳送資料
        info = dict()
        info["status"] = "success"
        info["page"] = "/test/lyshark"
        return jsonify(info)

    else:
        return render_template("index.html")

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=False)

前後端傳送JSON資料

前端程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

    <script type="text/javascript">
        function SendAjax()
        {
            var username = $('input[name="username"]').val();
            var password = $('input[name="password"]').val();
            $.ajax({
                url:"/",
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                headers: {"Authorization": "1a2cEFgh"},                              <!--此處攜帶token-->
                data: JSON.stringify({"username":username,"password":password}),     <!--此處攜帶JSON-->
                success:function(result)
                {
                    console.log("狀態碼: " + result.status + " 頁面: " + result.page);
                },
                error:function()
                {
                     console.log("執行失敗了");
                }
            });
        }
    </script>

    <!--提交資料-->
    <form action="/" method="post">
        使用者賬號: <input type="text" placeholder="使用者賬號" name="username" /><br><br>
        使用者密碼: <input type="text" placeholder="使用者密碼" name="password" /><br><br>
        <input type="button" value="傳送資料" onclick="SendAjax()">
    </form>
</body>
</html>

Flask後端程式碼

from flask import Flask,render_template,request
from flask import jsonify

app = Flask(import_name=__name__,
            static_url_path='/python',   # 設定靜態檔案的存取url字首
            static_folder='static',      # 設定靜態檔案的資料夾
            template_folder='templates') # 設定模板檔案的資料夾

@app.route('/', methods=["GET","POST"])
def index():
    if request.method == "POST":
        # 接收資料
        token = request.headers.get("Authorization")
        json_value = request.get_json()
        print(f"token = {token} username = {json_value['username']} password = {json_value['password']}")

        # 傳送資料
        info = dict()
        info["status"] = "success"
        info["page"] = "/route/lyshark"
        return jsonify(info)

    else:
        return render_template("index.html")

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=False)

傳送資料並攜帶token

前端程式碼部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        function SendAjax(){
            var token = $('input[name="token"]').val();
            $.ajax({
                url:"./dataFromAjax",
                type: "POST",
                contentType: "application/json;charset=utf-8",
                headers:{"Authorization":token},   <!--此處攜帶token-->
                success:function(result){
                    alert("執行成功...");
                },
                error:function(){
                     alert("執行失敗了...");
                }
            });
        }
    </script>

    <!--提交資料-->
    <form action="/dataFromAjax" method="post">
        設定token: <input type="text" placeholder="使用者賬號" name="token" /><br>
        <input type="button" value="傳送資料" onclick="SendAjax()">
    </form>
</body>
</html>

Flask後臺部分

from flask import Flask,render_template,request
from flask import jsonify

app = Flask(import_name=__name__,
            static_url_path='/python',   # 設定靜態檔案的存取url字首
            static_folder='static',      # 設定靜態檔案的資料夾
            template_folder='templates') # 設定模板檔案的資料夾

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/dataFromAjax",methods=['POST'])
def recv():
    token = request.headers.get("Authorization")
    print(token)
    return  render_template("index.html")

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=False)

收發JSON格式字串

前端部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        function GetAjax(){
            $.ajax({
                url:"/dataFromAjax",
                contentType: "GET",
                success:function(data){
                    alert("姓名: " + data.name + "年齡: " + data.age);
                },
                error:function(){
                    alert("執行失敗了...")
                }
            });
        }
    </script>

    <!--提交資料-->
    <input type="button" class="MyButton" value="接收資料" onclick="GetAjax()">
</body>
</html>

Flask後端部分

from flask import Flask,render_template,request
from flask import jsonify

app = Flask(import_name=__name__,
            static_url_path='/python',   # 設定靜態檔案的存取url字首
            static_folder='static',      # 設定靜態檔案的資料夾
            template_folder='templates') # 設定模板檔案的資料夾

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/dataFromAjax",methods=["GET","POST"])
def set():
    info = dict()
    info['name'] = "lyshark"
    info['age'] = 22
    return jsonify(info)

if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=False)

以上就是Flask框架運用Ajax實現資料互動的範例程式碼的詳細內容,更多關於Flask Ajax資料互動的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com