前後臺交互,傳參是必不可少的,來說一說Falsk中常用的傳參方式。
在JS中使用POST ajax傳參
在js中將參數封裝成json字符串,使用POST方法訪問路由函數。獲取參數並處理
var data = {
a: a,
b: b
}
$.ajax({
type: "POST",
url: "/blog/blog",
data: JSON.stringify(data),
contentType: 'application/json; charset=UTF-8', //發送json數據
datatype: 'json', //希望服務器返回json數據
success: function (data) {},
error: function () {}
});
後臺接受參數
from flask import request
import json
blog.route("/blog", methods=["POST"])
def blog():
data = request.data
json_data = json.loads(data.decode("utf-8"))
a = json_data.get("a", None)
b = json_data.get("b", None)
在JS中使用GET url傳參
在js中直接使用window.location.replace()方法跳轉,並將參數寫入url傳到後臺的方法
window.location.replace("/blog/blog/" + 1)
路由函數
blog.route("/blog/<int:id>", methods=["GET"])
def blog(id):
print(id)
在HTML中使用jinjia2語法 url傳參
在html中使用jinjia2語法 url_for 跳轉,使用url傳參
<a href="{{ url_for('blogmain.index', id=1) }}">博客</a>
路由函數
blog.route("/blog/<int:id>", methods=["GET"])
def blog(id):
print(id)