Python and js interactive call method

The background code is used

  1. [Get method] use jquery's get json to interact with the background

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)
  1. [Universal way] Use jquery's ajax to interact with the background, set different parameters, you can get or post

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)
  1. Use ajax to supplement an example of post method

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

Python and js interactive call method
Python and Go
Least squares method and its python implementation details
Python memory mapped file read and write method
Python introspection and reflection
Python magic method topic
Python object-oriented magic method
Python3.7 debugging example method
[python] python2 and python3 under ubuntu
Python function-dictionary get() method
Python error handling method
Python deconstruction and packaging
Python3 configuration and entry.md
Python defines a function method
Python automated operation and maintenance 2
Python introduction and environment installation
Python know crawler and anti crawler
Python TCP packet injection method
centos7 install python3 and ipython
Python drawing ring graph method
Python tracking except information method
ubuntu18.04 compile and install python3.8
Analysis of JS of Python crawler
Centos 6.10 reinstall python and yum
Python open read and write
Python&#39;s Jenkins interface call method
CentOS7 install python3 and pip3
Python automated operation and maintenance 1
Python data structure and algorithm
Python multi-process and multi-thread basics
CentOS 6.9 compile and install python
Python implements gradient descent method
CentOS 6 compile and install python 3
Python right alignment example method
Python method of parameter passing
Generators and iterators in Python
Python arithmetic sequence calculation method
python tutorial | The most standard map call method (data provided by the National Bureau of Surveying and Mapping)
python tutorial | The most standard map call method (data provided by the National Bureau of Surveying and Mapping)
python tutorial | The most standard map call method (data provided by the National Bureau of Surveying and Mapping)