【问题标题】:Issue making an AJAX call to flask render_template对烧瓶 render_template 进行 AJAX 调用时出现问题
【发布时间】: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 时,选择任一单选按钮会将值更改为12,但我无法再次选择任一单选按钮。该页面将挂在第二个选择上,我不确定发生了什么。

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

【问题讨论】:

    标签: javascript python jquery html flask


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2012-06-20
      • 2014-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      相关资源
      最近更新 更多