假设我在页面底部有两个单选按钮(分别标记为1和2)和一些文本。默认情况下,该文本的值为RaidEvent
,并且未选中任何复选框。如果单击单选按钮之一,则要根据所选的单选输入将文本的值更改为1或2。为此,我将代码基于AJAX call described here。这是代码:
-1
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
,但是我无法第二次选择任何一个单选按钮。该页面将挂在第二个选择上,我不确定发生了什么。
注意:尽管这看起来有些过分,但是在我正在从事的较大项目中,我的表单提交更为复杂,这只是MVCE。
答案 0 :(得分:1)
由于创建了动态内容,因此需要将change
事件处理程序锚定到外部标记:
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"> </script>
<body>
<div class='wrapper'>
<form>
<input name="level" type="radio" id="1">1</input>
<input name="level" type="radio" id="2">2</input>
</form>
<p>{{ value }}</p>
</div>
</body>
<script>
$(document).ready(function(){
$('.wrapper').on('change', 'input[type=radio]', function(){
console.log( $( this ).attr("id"));
$.ajax({
type: "POST",
data: { level: $( this ).attr("id") },
success: function(response) {
console.log("HERE");
$('p').text(response.toString());
},
});
});
});
</script>
</html>