Try   HackMD

flask框架 - 前端傳送後端

參考網站

框架介紹

用 python 撰寫的 Web 應用框架

使用flask的前置作業

  1. 安裝flask模塊
pip install flask
  1. 建立資料夾

    • templates 存放 html
    • static 存放 css、js和照片
    • Image Not Showing Possible Reasons
      • The image file may be corrupted
      • The server hosting the image is unavailable
      • The image path is incorrect
      • The image format is not supported
      Learn More →
  2. 注意 flask 要用的 port 有沒有被占用(falsk 要用的 port 寫在 python 裡)

    • 例如: xampp 已經占用 port:8080 就不可以用 8080 ,可以改用 8000
      Image Not Showing Possible Reasons
      • The image file may be corrupted
      • The server hosting the image is unavailable
      • The image path is incorrect
      • The image format is not supported
      Learn More →

實際操作應用(範例)

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--引入jQuery包用于使用ajax--> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <meta charset="UTF-8"> <title>Document</title> </head> <body> <h1>請輸入你的姓名和年齡</h1> <!--創建兩個input輸入框,定義id分別為name,age--> <input type="text" id="name" name="name" placeholder="姓名"> <br> <input type="text" id="age" name="age" placeholder="年齡"> <br> <!--創建button按鈕,點擊則激發submit()事件--> <button onclick="submit();">提交</button> <script> /*在這里撰寫submit()事件*/ function submit() { $.ajax({ url: "submit", /*資料提交到submit處*/ type: "GET", /*采用POST方法提交*/ data: { "name": $("#name").val(),"age":$("#age").val()}, /*提交的資料(json格式),從輸入框中獲取*/ /*result為后端函式回傳的json*/ success: function (result) { if (result.message == "success!") { alert(result.message+"你的名字是"+result.name+",你的年齡是"+result.age) } else { alert(result.message) } } }); } </script> </body> </html>
app. py
  • 通常當作主程式
from flask import Flask, render_template, request, jsonify #創建Flask物件app并初始化 app = Flask(__name__) #通過python裝飾器的方法定義路由地址 @app.route("/") #定義方法 **用jinjia2引擎來渲染頁面**,并回傳一個index.html頁面 def root(): return render_template("index.html") #app的路由地址"/submit"即為ajax中定義的url地址,采用POST、GET方法均可提交 @app.route("/submit",methods=["GET", "POST"]) #從這里定義具體的函式 回傳值均為json格式 def submit(): #由于POST、GET獲取資料的方式不同,需要使用if陳述句進行判斷 if request.method == "POST": # 從前端拿數據 name = request.form.get("name") age = request.form.get("age") if request.method == "GET": name = request.args.get("name") age = request.args.get("age") #如果獲取的資料為空 if len(name) == 0 or len(age) == 0: # 回傳的形式為 json return {'message':"error!"} else: return {'message':"success!",'name':name,'age':age} if __name__ == '__main__': #定義app在8080埠運行 app.run(host="localhost",port=8000,debug=True)

開啟網頁的方式

操作頁面
  1. 在 cmd 打開 app.py如下圖

  2. 在瀏覽器輸入 localhost:8000/看自己設定的路徑(圖一的第6行),若只有斜線就打 localhost:8000 就好(圖二)

  • 圖一
    圖一
  • 圖二
    圖二
  1. 輸入成功畫面
  • 圖三
    圖三

額外補充 (js 傳送資料到後端 php 的方式)

let xmlhttp = new XMLHttpRequest(); // 發送請求到哪裡open(用甚麼方式請求、向誰請求、是否要用非同步) // 請求方式:POST、GET xmlhttp.open("get", `readFolder.php?id=${id}`, true); //post 告知後端 //告訴後端是用 JSON 格式 xmlhttp.setRequestHeader("Content-type", "application/json"); //將物件資料轉成字串 var data = JSON.stringify(account); //送出data到後端 xmlhttp.send(); // 監聽讀取 xmlhttp.onload = function () { // 從後端拿到的資料 let data = xmlhttp.responseText; data = data.replace("\r\n",""); imgData = data.split(","); for (let i = 0;i<imgData.length;i++){ console.log("data:",imgData[i]); } }