核心代碼:
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()
<!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>
效果截圖: