python和js交互調(diào)用的方法
后臺(tái)代碼都是利用的
1.【get方式】使用jquery的get json與后臺(tái)交互
前端js代碼片段
var data= { 'a': $('input[name="a"]').val(), 'b': $('input[name="b"]').val() } $.getJSON($SCRIPT_ROOT + '/_add_numbers',data, function(data) { $('#result').text(data.result); $('input[name=a]').focus().select(); });
后端pthon代碼如下
# ajax,Get方式與js交互(非表單)采用了flask框架@app.route('/_add_numbers')def add_numbers(): """Add two numbers server side, ridiculous but well...""" a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) log.info(a) log.info(b) return jsonify(result=a + b)
2.【萬能方式】使用jquery的ajax與后臺(tái)交互,設(shè)置不同的參數(shù),可以get也可以post
上面的例子用ajax方式,前端代碼如下
var data= { 'a': $('input[name="a"]').val(), 'b': $('input[name="b"]').val() } {# $.getJSON($SCRIPT_ROOT + '/_add_numbers',data, function(data) {#} {# $('#result').text(data.result);#} {# $('input[name=a]').focus().select();#} {# });#} $.ajax({ type: 'get', url: $SCRIPT_ROOT + '/_add_numbers', data: data, contentType: 'application/json; charset=UTF-8', dataType: 'json', success: function(data) { $('#result').text(data.result); $('input[name=a]').focus().select(); }, error: function(xhr, type,xxx) { alert('error ') } });
后臺(tái)代碼不便依然是
# ajax,Get方式與js交互(非表單)@app.route('/_add_numbers')def add_numbers(): """Add two numbers server side, ridiculous but well...""" a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) log.info(a) log.info(b) return jsonify(result=a + b)
3.用ajax補(bǔ)充一個(gè)post方式的例子
前端js如下
function testmethod () { alert('rabbit'); var data = { "name": "test" } $.ajax({ type: 'POST', url: '/login', data:data, contentType: 'application/json; charset=UTF-8', dataType: 'json', success: function(data) { $('#result').text(data.username); }, error: function(xhr, type) { alert('error ') } }); }
后臺(tái)代碼如下:
# ajax ,post方式與js交互(表單提交) @app.route('/login',methods=['POST']) def login(): log.info('lalal') return jsonify(username='xixi',pwd='123')
這樣就很輕松的實(shí)現(xiàn)了前端與后臺(tái)的交互
本質(zhì)上,前端與后端交互都是通過json完成的
至于表單提交,就不需要寫js了,在form表單里面有有一個(gè)submit類型按鈕,點(diǎn)擊時(shí),會(huì)自動(dòng)提交到后臺(tái)對(duì)應(yīng)的路由上進(jìn)行處理。對(duì)于表單提交,后臺(tái)可以用
s=request.form.get('username',None)
來捕捉前端網(wǎng)頁的值。但是如果是非表單提交,則需要用js獲取值后,通過data參數(shù)傳入到后端才行。
實(shí)例擴(kuò)展:
python使用flask與js進(jìn)行前后臺(tái)交互的例子
flask與js進(jìn)行前后臺(tái)交互代碼如下,后臺(tái)給前端發(fā)數(shù)據(jù):
python部分:
# -*- coding: utf-8 -*- from flask import Flask,jsonify,render_template import json app = Flask(__name__)#實(shí)例化app對(duì)象 testInfo = {} @app.route('/test_post/nn',methods=['GET','POST'])#路由 def test_post(): testInfo['name'] = 'xiaoming' testInfo['age'] = '28' return json.dumps(testInfo) @app.route('/') def hello_world(): return 'Hello World!' @app.route('/index') def index(): return render_template('index.html') if __name__ == '__main__': app.run(host='0.0.0.0',#任何ip都可以訪問 port=7777,#端口 debug=True )
js部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>echarts</title> <style type="text/css"> html, body { width: 100%; height: 100%; } body { margin: 0px; padding: 0px } div { float: left; } #container { width: 50%; height: 100%; } #info { padding: 10px 20px; } </style> </head> <body> <div id="container"></div> <div id="info">數(shù)據(jù)展示:</div> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script> <script> $.ajax({ url: "test_post/nn", type: "POST", dataType: "json", success: function (data) { console.log(data) } }) </script> </body> </html>
到此這篇關(guān)于python和js交互調(diào)用的方法的文章就介紹到這了,更多相關(guān)python和js如何交互內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python數(shù)據(jù)可視化制作全球地震散點(diǎn)圖
這篇文章主要介紹了Python數(shù)據(jù)可視化制作全球地震散點(diǎn)圖,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08利用Python實(shí)現(xiàn)快速批量轉(zhuǎn)換HEIC文件
HEIC 是蘋果采用的新的默認(rèn)圖片格式,它能在不損失圖片畫質(zhì)的情況下,減少圖片大小。本篇文章將使用 Python 批量實(shí)現(xiàn) HEIC 圖片文件的格式轉(zhuǎn)換,需要的可以參考一下2022-07-07python PyQt5事件機(jī)制和定時(shí)器原理分析及用法詳解
PyQt為事件處理提供了兩種機(jī)制:高級(jí)的信號(hào)與槽機(jī)制,以及低級(jí)的事件處理機(jī)制,在基于PyQt5的應(yīng)用程序開發(fā)過程中經(jīng)常會(huì)遇到一些需要循環(huán)執(zhí)行的任務(wù),即定時(shí)多長(zhǎng)時(shí)間任務(wù)循環(huán)一次,本文給大家介紹了python PyQt5事件機(jī)制和定時(shí)器原理和用法,需要的朋友可以參考下2024-07-07Python的經(jīng)緯度與xy坐標(biāo)系相互轉(zhuǎn)換方式
這篇文章主要介紹了Python的經(jīng)緯度與xy坐標(biāo)系相互轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02LyScript實(shí)現(xiàn)計(jì)算片段Hash并寫出Excel的示例代碼
本案例將學(xué)習(xí)運(yùn)用LyScript計(jì)算特定程序中特定某些片段的Hash特征值,并通過xlsxwriter這個(gè)第三方模塊將計(jì)算到的hash值存儲(chǔ)成一個(gè)excel表格,感興趣的可以跟隨小編一起學(xué)習(xí)一下2022-09-09Python入門教程 超詳細(xì)1小時(shí)學(xué)會(huì)Python
本文適合有經(jīng)驗(yàn)的程序員盡快進(jìn)入Python世界.特別地,如果你掌握J(rèn)ava和Javascript,不用1小時(shí)你就可以用Python快速流暢地寫有用的Python程序.2006-09-09Pycharm學(xué)習(xí)教程(6) Pycharm作為Vim編輯器使用
這篇文章主要為大家詳細(xì)介紹了最全的Pycharm學(xué)習(xí)教程第六篇,Pycharm作為Vim編輯器使用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05