1 话不多说,直接上例子
- Sijax
# Sijax代表'Simple Ajax',它是一个Python/jQuery库,
# 旨在轻松地将Ajax引入到应用程序。它使用jQuery.ajax来发出AJAX请求。
import os
import flask_sijax
from flask import Flask, g, render_template
# 对象g挂载用户数据
from flask_sijax import sijax
path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax')
app = Flask(__name__)
app.config['SIJAX_STATIC_PATH'] = path
app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js'
flask_sijax.Sijax(app)
@app.route('/')
def index():
return "Hello World!<br><a href='/hello'>Go to Sijax test</a>"
# 使View函数能够处理Sijax请求
# 使用@app.route('/url',methods = [\'GET\' ,\'POST\'])或使用@flask_sijax.route辅助装饰器
@flask_sijax.route(app, '/hello')
def hello():
def say_hi(obj_response, arg):
# 'obj_response'参数是函数回复浏览器的方式。
obj_response.alert('Hi there!%s' % arg)
# print(g.sijax.is_sijax_request)
if g.sijax.is_sijax_request:
# Sijax request detected - let Sijax handle it
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template('sijaxexample.html')
if __name__ == '__main__':
app.run(debug=True)
- sijaxexample
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{# 调用百度的jQuery加速 #}
<script type="text/javascript" src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
{# 安装Flask-sijax时默认安装的sijax.js #}
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
{# 使用过滤器safe禁止转译sijax.get_js()值 #}
<script type="text/javascript"> {{ g.sijax.get_js()|safe }} </script>
<title>sijaxexample</title>
</head>
<body>
<form id="my_form">
<input type="text" name="tbx1" value="textbox 1">
<input type="text" name="tbx2" value="textbox 2">
<input type="checkbox" name="cbx" value="checked">
</form>
<script type="text/javascript">
let values=Sijax.getFormValues('#my_form')
</script>
<a href="javascript://" onclick="Sijax.request('say_hi',[values]);">click</a>
</body>
</html>
2 结果图