对烧瓶render_template进行 AJAX 调用时出现问题



假设我有两个单选按钮(标记为 1 和 2)和页面底部的一些文本。默认情况下,文本的值-1,并且不选中任何复选框。如果我单击其中一个单选按钮,我想根据所选的单选输入将文本的值更改为 1 或 2。为此,我基于此处描述的 AJAX 调用编写了代码。这是代码:

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时,选择任一单选按钮会将值更改为12但我无法再次选择任一单选按钮。该页面将挂在第二个选择上,我不确定发生了什么。

注意:虽然这看起来有点矫枉过正,但我在我正在处理的更大项目中有一个更复杂的表单提交,这只是一个 MVCE。

由于存在动态内容创建,因此需要将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>

最新更新