-## download:Python 操作三大主流数据库 实战网易新闻客户端 后台代码都是应用的
1.【get 方式】运用 jquery 的 get json 与后台交互
前端 js 代码片段
? 1 2 3 4 5 6 7 8 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 代码如下
? 1 2 3 4 5 6
"""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 方式,前端代码如下
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 ') } }); 后台代码不便仍然是
? 1 2 3 4 5 6
"""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 如下
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 ') } }); } 后台代码如下:
? 1 2 3 4 5
@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 局部:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
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 局部: