首页 > 解决方案 > 对烧瓶 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,选择任一单选按钮会将值更改为1or2但我无法再次选择任一单选按钮。该页面将挂在第二个选择上,我不确定发生了什么。

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

标签: javascriptpythonjqueryhtmlflask

解决方案


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

推荐阅读