0
在Flask網站上有一個關於如何使用AJAX的教程,這是一個示例來顯示兩個數字的總和。填寫表單時AJAX + Flask更新服務器請求
這是Python應用程序 從瓶進口瓶,render_template,請求jsonify
# Initialize the Flask application
app = Flask(__name__)
@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)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80"),
debug=True
)
這是HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"
rel="stylesheet">
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON('/_add_numbers', {
a: $('input[name="a"]').val(),
b: $('input[name="b"]').val()
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<h3 class="text-muted">How To Manage JSON Requests</h3>
</div>
<hr/>
<div>
<p>
<input type="text" size="5" name="a"> +
<input type="text" size="5" name="b"> =
<span id="result">?</span>
<p><a href="javascript:void();" id="calculate">calculate server side</a>
</form>
</div>
</div>
</body>
</html>
我看到這個例子之一是能夠發送每次點擊鏈接時向服務器發送請求,但是,我想知道是否有可能跳過此步驟並且請求超時,用戶輸入的文本會發生變化。
感謝,它看起來像它的工作,但只有當我按下回車鍵或點擊我出的輸入框:/。我希望可以在表單中輸入時調用服務器。 – Brian
編輯檢查,當你輸入... – GAEfan
在這裏使用油門功能,以保持呼叫數... \ – reptilicus