【发布时间】:2019-01-30 01:03:26
【问题描述】:
假设我有两个单选按钮(标记为 1 和 2)和页面底部的一些文本。默认情况下,文本的值为-1,并且未选中任何复选框。如果单击其中一个单选按钮,我想将文本的值更改为 1 或 2,具体取决于所选的单选输入。为此,我将代码基于AJAX call described here。代码如下:
hello.py
from flask import (
Flask, render_template, request
)
app = Flask(__name__)
@app.route('/', methods=('GET', 'POST'))
def hello():
level = -1
print(request.method)
if request.method == 'POST':
level = int(request.form.get('level', False))
return render_template('test.html', value=level)
templates/test.html
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<body>
<form>
<input name="level" type="radio" id="1">1</input>
<input name="level" type="radio" id="2">2</input>
</form>
{{ value }}
</body>
<script>
$(function() {
$('input[type=radio]').change(function() {
console.log( $( this ).attr("id"));
$.ajax({
type: "POST",
data: { level: $( this ).attr("id") },
success: function(response) {
console.log("HERE");
document.write(response);
},
});
});
});
</script>
</html>
当我调用flask run 时,选择任一单选按钮会将值更改为1 或2,但我无法再次选择任一单选按钮。该页面将挂在第二个选择上,我不确定发生了什么。
注意:虽然这看起来有点矫枉过正,但在我正在处理的较大项目中,我有一个更复杂的表单提交,这只是一个 MVCE。
【问题讨论】:
标签: javascript python jquery html flask