The background code is used
Front-end js code snippet
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();});
The back-end pthon code is as follows
# Ajax, Get way to interact with js(Non-form) uses the flask [email protected]('/_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)returnjsonify(result=a + b)
The above example uses ajax, the front-end code is as follows
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 ')}});
Background code inconvenience is still
# Ajax, Get way to interact with js(Non-form)@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)returnjsonify(result=a + b)
The front-end js is as follows
functiontestmethod(){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 ')}});}
The background code is as follows:
# ajax, post mode and js interaction (form submission)
@ app.route('/login',methods=['POST'])
def login():
log.info('lalal')returnjsonify(username='xixi',pwd='123')
In this way, the front-end and back-end interaction is easily realized
Essentially, the front-end and back-end interactions are all done through json
As for form submission, there is no need to write js. There is a submit type button in the form form. When clicked, it will be automatically submitted to the corresponding route in the background for processing. For form submission, the background can use
s=request.form.get('username',None)
To capture the value of the front-end web page. But if it is a non-form submission, you need to use js to get the value and pass it to the backend through the data parameter.
Example extension:
An example of python using flask and js for front and back interaction
The front-end and back-end interaction code between flask and js is as follows, and the back-end sends data to the front-end:
python part:
# - *- coding: utf-8-*-from flask import Flask,jsonify,render_template
import json
app =Flask(__name__)#Instantiate app object
testInfo ={}
@ app.route('/test_post/nn',methods=['GET','POST'])#routing
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():returnrender_template('index.html')if __name__ =='__main__':
app.run(host='0.0.0.0',#Any ip can access
port=7777,#port
debug=True
)
js part:
<! 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"data demonstration:</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
So far, this article on the method of interactive calling between python and js is introduced. For more related content on how to interact with python and js, please search for ZaLou.Cn's previous articles or continue to browse the related articles below. Hope you will support ZaLou more in the future. .Cn!
Recommended Posts