【问题标题】:Ajax after form submit表单提交后的Ajax
【发布时间】:2021-08-17 01:59:07
【问题描述】:

在成功提交表单发布后如何进行 ajax 发布。我想获取表单上提交的输入,根据该输入进行一些计算,并将结果显示在前端而不刷新页面。

烧瓶

@app.route('/', methods=['GET', 'POST'])
def app_home():
    if request.method == 'POST':
        input_amount = request.form['input_amount']
        input_amount = float(input_amount)

        amount1 = input_amount * 12
        amount2 = input_amount * 10

        return render_template("index.html", amount1=amount1,amount2=amount2,)

    return render_template("index.html")

if __name__ == '__main__':
    app.run(debug=True)

index.html

    <form method="post">
        <div class="mb-3">
            <label>Enter amount</label>
            <input name = "input_amount" type="text" class="form-control" placeholder="amount">
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
    </form>

    
    <div class="container">
        <p id = "response">result is: ${{amount1}}</p>
        <p id = "response">result is: ${{amount2}}</p>
    </div>

AJAX 请求

<script>
   $(document).ready(function () {
        $('form').on('submit', function (event) {
            $.ajax({
                data: { input_amount : input_amount},
                type: 'POST',
                url: '/'
            })
                .done(function (data) {
                    $('#response').text(data.output).show();
                    
                });
            event.preventDefault();
        });
    });
</script>

【问题讨论】:

  • 您需要不同的设置。正确的流程如下: (1) 用户通过 Flask 函数请求网页,该函数通过render_template 函数返回; (2) 用户输入内容并按下“提交”按钮,该按钮激活一个 Javascript 函数,该函数将 POST 请求发送到返回json另一个 Flask 函数(计算发生在此步骤的 Python 部分) ; (3) JS函数获取返回的json并相应更新网页。

标签: python ajax flask


【解决方案1】:

根据documentation,正确的方法是不使用表单。说实话,您不想提交表格,对吧?您只想传递输入值。

所以我尝试了文档代码(因为我也在为我的应用程序研究这个“ajax + flask 连接”),这应该可以回答你的问题。制作了一个按钮类,因为您(和我)更喜欢按钮而不是链接。

app.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)

@app.route('/_add_numbers')
def add_numbers():
    a = request.args.get('a', 0, type=int)
    b = request.args.get('b', 0, type=int)
    return jsonify(result=a + b)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
   app.run(debug = True)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
      $SCRIPT_ROOT = {{ request.script_root|tojson }};
    </script>

    <title>Document</title>

    <style>
      .button {
        background-color: #5b4caf;
        border: none;
        color: white;
        padding: 0.75rem 0.75rem;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 14px;
        border-radius: 3px;
      }
    </style>
  </head>
  <body>
    <h1>jQuery Example</h1>
    <p>
      <input type="text" size="5" name="a" /> +
      <input type="text" size="5" name="b" /> = <span id="result">?</span>
    </p>

    <p>
      <a href="#" id="calculate" class="button">Calculate server side</a>

      <script>
        $(function () {
          $("a#calculate").bind("click", function () {
            $.getJSON(
              $SCRIPT_ROOT + "/_add_numbers",
              {
                a: $('input[name="a"]').val(),
                b: $('input[name="b"]').val(),
              },
              function (data) {
                $("#result").text(data.result);
              }
            );
            return false;
          });
        });
      </script>
    </p>
  </body>
</html>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多