在after_request事件中註冊您的默認回調,並檢查_callback
字典是否爲空,如果是,請在現有響應上註冊默認回調else通過。
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)
該解決方案完美的作品,除了註冊的所有回調執行兩次,因爲如果'g.sijax.is_sijax_request:...返回g.sijax.process_request()'使用了兩次。有沒有辦法解決這個問題? –
我更新了代碼。 – pjcunningham
謝謝,我只是實現了你的代碼,視圖中的回調工作。但是,如果在請求的視圖中也存在回調時使用'@ app.after_request'中的回調函數,則它們不起作用。 –