Ajax前后端交互——后端接收前端页面变量

核心代码:

  • app.py
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)


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

#接受前台消息
@app.route('/receive_message', methods=['GET'])
def send_message():
    global message_get    #定义全局对象(全局变量)
    message_get = ""      #初始化全局对象

    message_get = request.args['message']   #接受前台变量
    print("收到前端页面变量值:",message_get)
    # print("收到前端发过来的信息:%s" % message_get)
    return "数据传递成功!"


if __name__ == '__main__':
    app.run()
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <label for="send_content">向后台发送消息:</label>
    <input id="send_content" type="text" name="send_content">
    <input id="send" type="button" value="发送">
</div>

<script src="/static/js/jquery-3.6.0.min.js"></script>

<!-- 发送 -->
<script type="text/javascript">
    $("#send").click(function () {
        var message = $("#send_content").val()
        $.ajax({
            url:"http://127.0.0.1:5000/receive_message",
            type:"GET",
            data:{
                message:message
            },
            success:function (data) {
                alert(data)
            },
            error:function () {
                alert("接收失败")
            }
        })
    })
</script>

</body>
</html>

效果截图:

 

 

posted @ 2021-11-17 17:12  CherriesOvO  阅读(302)  评论(0编辑  收藏  举报