欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Flask框架運(yùn)用Axios庫實(shí)現(xiàn)前后端交互詳解

 更新時(shí)間:2022年12月22日 15:11:17   作者:LyShark  
Axios 是一個(gè)基于promise的HTTP庫,該庫是一個(gè)更好的替代ajax向后端發(fā)送數(shù)據(jù)或請(qǐng)求數(shù)據(jù)的前端組件庫。本文通過示例為大家介紹了如何運(yùn)用Axios庫實(shí)現(xiàn)前后端交互,感興趣的可以了解一下

Axios 是一個(gè)基于promise的HTTP庫,該庫是一個(gè)更好的替代ajax向后端發(fā)送數(shù)據(jù)或請(qǐng)求數(shù)據(jù)的前端組件庫,其本質(zhì)上也是對(duì)原生XHR的封裝,只不過它是Promise的實(shí)現(xiàn)版本,符合最新的ES規(guī)范,如下案例運(yùn)用axios向后端提交JSON字符串,后端通過Flask響應(yīng)請(qǐng)求并處理。

前端運(yùn)用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)

運(yùn)行后提交數(shù)據(jù)前后端均可接收到數(shù)據(jù):

到此這篇關(guān)于Flask框架運(yùn)用Axios庫實(shí)現(xiàn)前后端交互詳解的文章就介紹到這了,更多相關(guān)Flask Axios前后端交互內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論