Flask框架運(yùn)用Ajax實(shí)現(xiàn)數(shù)據(jù)交互的示例代碼
使用Ajax技術(shù)網(wǎng)頁(yè)應(yīng)用能夠快速地將增量更新呈現(xiàn)在用戶界面上,而不需要重載刷新整個(gè)頁(yè)面,這使得程序能夠更快地回應(yīng)用戶的操作,如下筆記將簡(jiǎn)單介紹使用AJAX如何實(shí)現(xiàn)前后端數(shù)據(jù)通信。
前后端發(fā)送字符串
前端代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> function SendAjax(){ $.ajax({ url:"/", contentType: "POST", data:{"head":"hello lyshark"}, success:function(data){ if(data=="1"){ alert("請(qǐng)求已經(jīng)提交."); } }, error:function(){ alert("執(zhí)行失敗了...") } }); } </script> <form action="/" method="post"> <input type="button" value="發(fā)送數(shù)據(jù)" onclick="SendAjax()"> </form> </body> </html>
Flask后端代碼
from flask import Flask,render_template,request import json app = Flask(import_name=__name__, static_url_path='/python', # 配置靜態(tài)文件的訪問(wèn)url前綴 static_folder='static', # 配置靜態(tài)文件的文件夾 template_folder='templates') # 配置模板文件的文件夾 @app.route('/', methods=["GET","POST"]) def index(): if request.method == "POST": # 接收數(shù)據(jù) token = request.headers.get("Authorization") json_value = request.get_json() print(f"token = {token} username = {json_value['username']} password = {json_value['password']}") # 發(fā)送數(shù)據(jù) info = dict() info["status"] = "success" info["page"] = "/test/lyshark" return jsonify(info) else: return render_template("index.html") if __name__ == '__main__': app.run(host="127.0.0.1", port=80, debug=False)
前后端發(fā)送JSON數(shù)據(jù)
前端代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> function SendAjax() { var username = $('input[name="username"]').val(); var password = $('input[name="password"]').val(); $.ajax({ url:"/", type: "POST", contentType: "application/json;charset=utf-8", dataType: "json", headers: {"Authorization": "1a2cEFgh"}, <!--此處攜帶token--> data: JSON.stringify({"username":username,"password":password}), <!--此處攜帶JSON--> success:function(result) { console.log("狀態(tài)碼: " + result.status + " 頁(yè)面: " + result.page); }, error:function() { console.log("執(zhí)行失敗了"); } }); } </script> <!--提交數(shù)據(jù)--> <form action="/" method="post"> 用戶賬號(hào): <input type="text" placeholder="用戶賬號(hào)" name="username" /><br><br> 用戶密碼: <input type="text" placeholder="用戶密碼" name="password" /><br><br> <input type="button" value="發(fā)送數(shù)據(jù)" onclick="SendAjax()"> </form> </body> </html>
Flask后端代碼
from flask import Flask,render_template,request from flask import jsonify app = Flask(import_name=__name__, static_url_path='/python', # 配置靜態(tài)文件的訪問(wèn)url前綴 static_folder='static', # 配置靜態(tài)文件的文件夾 template_folder='templates') # 配置模板文件的文件夾 @app.route('/', methods=["GET","POST"]) def index(): if request.method == "POST": # 接收數(shù)據(jù) token = request.headers.get("Authorization") json_value = request.get_json() print(f"token = {token} username = {json_value['username']} password = {json_value['password']}") # 發(fā)送數(shù)據(jù) info = dict() info["status"] = "success" info["page"] = "/route/lyshark" return jsonify(info) else: return render_template("index.html") if __name__ == '__main__': app.run(host="127.0.0.1", port=80, debug=False)
發(fā)送數(shù)據(jù)并攜帶token
前端代碼部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> function SendAjax(){ var token = $('input[name="token"]').val(); $.ajax({ url:"./dataFromAjax", type: "POST", contentType: "application/json;charset=utf-8", headers:{"Authorization":token}, <!--此處攜帶token--> success:function(result){ alert("執(zhí)行成功..."); }, error:function(){ alert("執(zhí)行失敗了..."); } }); } </script> <!--提交數(shù)據(jù)--> <form action="/dataFromAjax" method="post"> 設(shè)置token: <input type="text" placeholder="用戶賬號(hào)" name="token" /><br> <input type="button" value="發(fā)送數(shù)據(jù)" onclick="SendAjax()"> </form> </body> </html>
Flask后臺(tái)部分
from flask import Flask,render_template,request from flask import jsonify app = Flask(import_name=__name__, static_url_path='/python', # 配置靜態(tài)文件的訪問(wèn)url前綴 static_folder='static', # 配置靜態(tài)文件的文件夾 template_folder='templates') # 配置模板文件的文件夾 @app.route("/") def index(): return render_template("index.html") @app.route("/dataFromAjax",methods=['POST']) def recv(): token = request.headers.get("Authorization") print(token) return render_template("index.html") if __name__ == '__main__': app.run(host="127.0.0.1", port=80, debug=False)
收發(fā)JSON格式字符串
前端部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script> </head> <body> <script type="text/javascript"> function GetAjax(){ $.ajax({ url:"/dataFromAjax", contentType: "GET", success:function(data){ alert("姓名: " + data.name + "年齡: " + data.age); }, error:function(){ alert("執(zhí)行失敗了...") } }); } </script> <!--提交數(shù)據(jù)--> <input type="button" class="MyButton" value="接收數(shù)據(jù)" onclick="GetAjax()"> </body> </html>
Flask后端部分
from flask import Flask,render_template,request from flask import jsonify app = Flask(import_name=__name__, static_url_path='/python', # 配置靜態(tài)文件的訪問(wèn)url前綴 static_folder='static', # 配置靜態(tài)文件的文件夾 template_folder='templates') # 配置模板文件的文件夾 @app.route("/") def index(): return render_template("index.html") @app.route("/dataFromAjax",methods=["GET","POST"]) def set(): info = dict() info['name'] = "lyshark" info['age'] = 22 return jsonify(info) if __name__ == '__main__': app.run(host="127.0.0.1", port=80, debug=False)
以上就是Flask框架運(yùn)用Ajax實(shí)現(xiàn)數(shù)據(jù)交互的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于Flask Ajax數(shù)據(jù)交互的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
對(duì)python dataframe邏輯取值的方法詳解
今天小編就為大家分享一篇對(duì)python dataframe邏輯取值的方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01PyCharm 解決找不到新打開(kāi)項(xiàng)目的窗口問(wèn)題
這篇文章主要介紹了PyCharm 解決找不到新打開(kāi)項(xiàng)目的窗口問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究
這篇文章主要為大家介紹了Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Python遍歷pandas數(shù)據(jù)方法總結(jié)
本篇文章給大家詳細(xì)介紹了Python中遍歷pandas數(shù)據(jù)方法以及相關(guān)注意點(diǎn),對(duì)此有興趣的朋友參考學(xué)習(xí)下吧。2018-02-02Python實(shí)現(xiàn)爬蟲(chóng)抓取與讀寫、追加到excel文件操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)爬蟲(chóng)抓取與讀寫、追加到excel文件操作,結(jié)合具體實(shí)例形式分析了Python針對(duì)糗事百科的抓取與Excel文件讀寫相關(guān)操作技巧,需要的朋友可以參考下2018-06-06python對(duì)配置文件.ini進(jìn)行增刪改查操作的方法示例
.ini配置文件常被用作存儲(chǔ)程序中的一些參數(shù),通過(guò)它程序可以變得更加靈活。下面這篇文章主要給大家介紹了關(guān)于python對(duì)配置文件.ini進(jìn)行增刪改查操作的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-07-07PyHacker編寫指南引用Nmap模塊實(shí)現(xiàn)端口掃描器
這篇文章主要為大家介紹了PyHacker編寫指南Nmap模塊實(shí)現(xiàn)端口掃描,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05