python和js交互调用的方法

后台代码都是利用的
1.【get方式】使用jquery的get json与后台交互
前端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与后台交互,设置不同的参数,可以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 ')
}
});
 
后台代码不便依然是
# 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补充一个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 ')
}
});
}
 
后台代码如下:
# ajax ,post方式与js交互(表单提交)
@app.route('/login',methods=['POST'])
def login():
log.info('lalal')
return jsonify(username='xixi',pwd='123')
 
这样就很轻松的实现了前端与后台的交互
本质上,前端与后端交互都是通过json完成的
至于表单提交,就不需要写js了,在form表单里面有有一个submit类型按钮,点击时,会自动提交到后台对应的路由上进行处理。对于表单提交,后台可以用
s=request.form.get('username',None)
 
来捕捉前端网页的值。但是如果是非表单提交,则需要用js获取值后,通过data参数传入到后端才行。
实例扩展:
python使用flask与js进行前后台交互的例子
flask与js进行前后台交互代码如下,后台给前端发数据:
python部分:
# -*- coding: utf-8 -*-
from flask import Flask,jsonify,render_template
import json
 
app = Flask(__name__)#实例化app对象
 
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 {
100%;
height: 100%;
}
 
body {
margin: 0px;
padding: 0px
}
 
div {
float: left;
}
 
#container {
50%;
height: 100%;
}
 
#info {
padding: 10px 20px;
}
</style>
</head>
 
<body>
<div id="container"></div>
<div id="info">数据展示:</div>
<script>
$.ajax({
url: "test_post/nn",
type: "POST",
dataType: "json",
success: function (data) {
console.log(data)
}
})
 
</script>
 
</body>
 
</html>
 
到此这篇关于python和js交互调用的方法的文章就介绍到这了,更多相关python和js如何交互内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
每日分享,喜欢的看标题和多多点赞收藏加关注~~蟹蟹
原文地址:https://www.cnblogs.com/nanhe/p/13604827.html