极客大学-云原生训练营fg

download:极客大学-云原生训练营 后台代码都是应用的
1.【get方式】运用jquery的get json与后台交互
前端js代码片段
var data= https://www.it610.com/article/{
'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= https://www.it610.com/article/{

'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 ') } });

后台代码不便仍然是
?
1
2
3
4
5
6
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 = https://www.it610.com/article/{"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类型按钮,点击时,会自动提交到后台对应的路由上停止处置。关于表单提交,后台能够用
?
1
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')
【极客大学-云原生训练营fg】if name == '__main__':
app.run(host='0.0.0.0',#任何ip都能够访问
port=7777,#端口
debug=True
)
js局部:

    推荐阅读