Flask框架運用Axios庫實現(xiàn)前后端交互詳解
Axios 是一個基于promise的HTTP庫,該庫是一個更好的替代ajax向后端發(fā)送數(shù)據(jù)或請求數(shù)據(jù)的前端組件庫,其本質(zhì)上也是對原生XHR的封裝,只不過它是Promise的實現(xiàn)版本,符合最新的ES規(guī)范,如下案例運用axios向后端提交JSON字符串,后端通過Flask響應(yīng)請求并處理。
前端運用Axios發(fā)送數(shù)據(jù)的兩種方式。
<html>
<head>
<meta charset="UTF-8">
<title>LyShark</title>
<script src="https://cdn.lyshark.com/javascript/axios/0.26.0/axios.min.js"></script>
</head>
<body>
<input type="text" name="name" id="name" />
<input type="text" name="age" id="age" />
<button onclick="saveHanderPost()" >提交</button>
</body>
<!-- 第一種發(fā)送方法 -->
<script type="text/javascript">
function saveHanderPost()
{
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
axios.post("/",{
name:name,
age:age
})
.then(function(response){
console.log(response);
console.log(response.data.username);
console.log(response.data.message);
})
.catch(function(error){
console.log(error);
})
}
</script>
<!-- 第二種發(fā)送方法 -->
<script type="text/javascript">
function saveHanderPostB()
{
let name = document.getElementById("name").value;
let age = document.getElementById("age").value;
axios({
url: "/",
method: "post",
data: {
name: name,
age:age
},
responseType: "text/json",
})
.then(function(response){
console.log(response);
console.log(response.data.username);
console.log(response.data.message);
})
.catch(function(error){
console.log(error);
})
}
</script>
</html>Python后端使用Flask接收并處理前端發(fā)送過來的JSON字符串。
from flask import Flask,render_template,request
import json
app = Flask(import_name=__name__,
static_url_path='/python', # 配置靜態(tài)文件的訪問url前綴
static_folder='static', # 配置靜態(tài)文件的文件夾
template_folder='templates') # 配置模板文件的文件夾
@app.route('/', methods=["GET","POST"])
def index():
if request.method == "GET":
return render_template("index.html")
elif request.method == "POST":
val = request.get_json()
print("收到用戶: {} ---> 年齡: {}".format(val["name"],val["age"]))
# 返回JSON類型
return json.dumps({"username": "lyshark","message": "hello lyshark"})
if __name__ == '__main__':
app.run(host="127.0.0.1", port=80, debug=False)
運行后提交數(shù)據(jù)前后端均可接收到數(shù)據(jù):

到此這篇關(guān)于Flask框架運用Axios庫實現(xiàn)前后端交互詳解的文章就介紹到這了,更多相關(guān)Flask Axios前后端交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
TF-IDF與余弦相似性的應(yīng)用(一) 自動提取關(guān)鍵詞
這篇文章主要為大家詳細介紹了TF-IDF與余弦相似性的應(yīng)用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
python監(jiān)控linux內(nèi)存并寫入mongodb(推薦)
這篇文章主要介紹了python監(jiān)控linux內(nèi)存并寫入mongodb的相關(guān)資料,需要的朋友可以參考下2017-09-09
python傳到前端的數(shù)據(jù),雙引號被轉(zhuǎn)義的問題
這篇文章主要介紹了python傳到前端的數(shù)據(jù),雙引號被轉(zhuǎn)義的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
python爬蟲利用selenium實現(xiàn)自動翻頁爬取某魚數(shù)據(jù)的思路詳解
這篇文章主要介紹了python爬蟲利用selenium實現(xiàn)自動翻頁爬取某魚數(shù)據(jù)的思路詳解,本文給大家介紹的非常詳細,對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

