在 after_request 事件中注册您的默认回调并检查_callback
字典是否为空,如果是,则注册默认回调,否则传递现有响应。
import os
from flask import Flask, g, render_template_string
import flask_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.after_request
def after_request(response):
def alert(obj_response):
print 'Message from standard callback'
obj_response.alert('Message from standard callback')
if g.sijax.is_sijax_request:
if not g.sijax._sijax._callbacks:
g.sijax.register_callback('alert', alert)
return g.sijax.process_request()
else:
return response
else:
return response
_index_html = '''
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript"> {{ g.sijax.get_js()|safe }}</script>
</head>
<body>
<a href="javascript://" onclick="Sijax.request('alert');">Click here</a>
</body>
</html>
'''
_hello_html = '''
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
<script type="text/javascript"> {{ g.sijax.get_js()|safe }}</script>
</head>
<body>
<a href="javascript://" onclick="Sijax.request('say_hi');">Click here</a>
</body>
</html>
'''
@app.route('/')
def index():
return render_template_string(_index_html)
@flask_sijax.route(app, '/hello')
def hello():
def say_hi(obj_response):
print 'Message from hello callback'
obj_response.alert('Hi there from hello callback!')
if g.sijax.is_sijax_request:
g.sijax._sijax._callbacks = {}
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template_string(_hello_html)
if __name__ == '__main__':
app.run(port=7777, debug=True)