我正在使用Flask編寫Web應用程序,並且想要在Brython中使用browser.ajax功能,但找不到可行的示例。如果有人演示如何在Brython中使用ajax的簡單示例,那將會非常好。更具體地說,如何通過點擊提交按鈕將用戶輸入的數據傳遞到文本區。任何幫助,高度讚賞!如何在Brython中使用ajax
(我正在寫這幾個星期後,我發佈上述問題)。我按照本教程介紹瞭如何在Flask中實現ajax(http://runnable.com/UiPhLHanceFYAAAP/how-to-perform-ajax-in-flask-for-python),並嘗試用Brython替換jquery.ajax。不幸的是,我仍然無法工作。這裏是我的代碼:
瓶的部分:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)
Brython/HTML:
<body onload="brython()">
<script type="text/python">
from browser import document as doc
from browser import ajax
def on_complete(req):
if req.status==200 or req.status==0:
doc["txt_area"].html = req.text
else:
doc["txt_area"].html = "error "+req.text
def get(url):
req = ajax.ajax()
a = doc['A'].value
b = doc['B'].value
req.bind('complete',on_complete)
req.open('GET',url,True)
req.set_header('content-type','application/x-www-form-urlencoded')
req.send({"a": a, "b":b})
doc['calculate'].bind('click',lambda ev:get('/_add_numbers'))
</script>
<div class="container">
<div class="header">
<h3 class="text-muted">How To Manage JSON Requests</h3>
</div>
<hr/>
<div>
<p>
<input type="text" id="A" size="5" name="a"> +
<input type="text" id ="B" size="5" name="b"> =
<textarea type="number" class="form-control" id="txt_area" cols="10" rows = '10'></textarea>
<p><a href="javascript:void();" id="calculate">calculate server side</a>
</div>
</div>
</body>
</html>
我得到的是 「結果」:0。它看起來像brython不會發送數據到Flask的視圖函數,但我不知道如何解決這個問題。所以,如果有人能指出我究竟做錯了什麼,那將是很棒的。
非常感謝!有用!我唯一的問題是:是否需要在查詢字符串中手動包含參數(在本例中爲「?a =%s&b =%s」),或者它可以自動完成?再次,非常感謝! – chemist 2014-12-03 15:38:42
你應該更喜歡Post方法。無論哪種方式,是的,參數必須包含「手動」 - 瀏覽器只「知道」收集表單值並在重新加載整個頁面的事件中提交它們。 – jsbueno 2015-01-26 16:15:59