前端JavaScript代碼:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//--------------------------------------------GET請求
alert("GET");
$.ajax({
??????????type:"GET",
??????????url:"http://127.0.0.1:5000/login?pin=PIG",? ?? //請求地址替換成自己的地址
??????????<!--dataType:"json",-->
??????????success:function(data){
??????alert("GET:"+JSON.stringify(data));
??????????},
??????????error:function(jqXHR){
??????????????alert("Error: "+jqXHR.status);
??????????}
??????});
//--------------------------------------------POST請求
alert("POST");
$.ajax({
??????????type:"POST",
??????????url:"http://127.0.0.1:5000/login",? ? ?//請求地址替換成自己的地址
??????????dataType:"json",
??????????data:{
??????? ???? ?"pin": "wenru",
????? ????? ??"name": "chenchao"
??? ??? ???},
??????????success:function(data){
???????? ??? ?alert("POST:"+JSON.stringify(data));
??????????},
??????????error:function(jqXHR){
??????????????alert("Error: "+jqXHR.status);
??????????}
??????});
</script>
后端Python代碼:
flask接收前端請求并返回JSON串
views.py
# coding:utf8
import json?
from flask import render_template, request
from app.handler import errorres, successres #自己寫的兩個(gè)函數(shù)
#?獲取登錄名和登錄密碼
@home.route("/login", methods=["GET", "POST"])? ? ?#前端請求該地址?? http://127.0.0.1:5000/login
def login():
????# 獲取請求參數(shù)?? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ?? ?
????requestArgs = request.values??
? ? # request.values.get("key") 獲取所有參數(shù)
????# 獲取請求方法 request.method
????pin = requestArgs.get("pin") #不存在時(shí)返回None
????pwd = requestArgs.get("pwd")
? ? #校驗(yàn)用戶名和密碼是否存在
?? ?if pwd == None:
?????? ?print(">>>>", "none pwd")
?????? ?return errorres("None pwd")
?? ?elif pin == None:
?????? ?print(">>>>", "none pin")
?????? ?return errorres("None pin")
?? ?else:
?? ??? ?#返回json串
?????? ?res = jsonify({"pin": pin, "pwd": pwd})?
?? ??? ?return?res?? ??? ??
handler.py? (這個(gè)沒啥用)
#定義兩個(gè)統(tǒng)一的方法用來返回給前端:
#放在handler.py下
# coding:utf8
from flask import jsonify
def errorres(msg):
????return jsonify({"msg": msg, "status": 0})
def successres(data, msg=None, ):
????return jsonify({"msg": msg, "status": 1, "data": data})