使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载刷新整个页面,这使得程序能够更快地回应用户的操作,如下笔记将简单介绍使用AJAX如何实现前后端数据通信。
前后端发送字符串
前端代码
代码语言:javascript复制<!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后端代码
代码语言:javascript复制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数据
前端代码
代码语言:javascript复制<!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后端代码
代码语言:javascript复制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
前端代码部分
代码语言:javascript复制<!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后台部分
代码语言:javascript复制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格式字符串
前端部分
代码语言:javascript复制<!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后端部分
代码语言:javascript复制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)