前端:文章来源:https://www.toymoban.com/news/detail-766982.html
<!DOCTYPE html>
<html>
<head>
<title>发送数据到后端</title>
</head>
<body>
<div>
<input type="text" id = "userId">
</div>
<div>
<input type="password" id="password">
</div>
<button onclick="login()">login</button>
<script src="js/jquery.min.js"></script>
<script>
function login(){
var data = {
userId: $("#userId").val(),
password: $("#password").val()
};
$.ajax({
url:"http://localhost:5001/login",
type:"post",
dataType:"json",
//data为要传递给后端的数据,使用JSON.stringify()转换为json格式
data:JSON.stringify(data),
success:function (data){
console.log(data)
console.log(data.status)
console.log(data.time)
},
error:function (){
console.log("***********")
}
});
}
</script>
</body>
</html>
后端:文章来源地址https://www.toymoban.com/news/detail-766982.html
import datetime
import json
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def process():
data = request.get_data()
print(data)
json_data = json.loads(data)
print(json_data)
with open('example.txt', 'w',encoding='utf-8') as f:
x = json.dumps(json_data)
f.write(x)
Id = json_data.get("userId")
password = json_data.get("password")
print("userId is " + Id)
print("password is " + password)
# 给前端传输json数据
info = dict()
info['status'] = 'success'
info['time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return jsonify(info)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5001)
到了这里,关于python前后端简单交互的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!