首页 > 解决方案 > 如果我使用在 Chrome 中单击后禁用按钮的 jquery 功能,为什么表单输入提交按钮不发送请求?

问题描述

我有 Flask 应用程序,其中一个页面有表单,当我单击输入提交按钮时发送表单请求,我希望在单击后禁用输入按钮。为此,我编写了 jquery 函数并将其附加到输入元素。

一切都在 Edge 浏览器中完美运行,但是当我在 Chrome 中进行测试时,按钮被禁用,但发布请求不会发送到服务器。

显示加载 gif 并阻止提交输入按钮的 jquery 脚本:

function loading() {
  if ($('#calendar1').val() && $('#calendar2').val()) {
    $("#loading").show();
    $("#content").hide();
    $(':input[type="submit"]').prop('disabled', true);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" class="ordinary_form" id="wifi_form">
  <label for="calendar1"> Choose time period start: </label>
  <input type="date" name="calendar1" id="calendar1" required> <br> <br>
  <label for="calendar2"> Choose time period end: </label>
  <input type="date" name="calendar2" id="calendar2" required></p>
  <label for="period"> Choose step: </label>
  <select required name="period" id="period">
    <option selected value="0">Day</option>
    <option value="1">Week</option>
    <option value="2">Month</option>
  </select>
  <br><br>
  <input target="_self" type="submit" value="Send" formtarget="{{url_for('wifi')}}" formmethod="post" onclick="loading();">
</form>

Python代码(我猜你不需要它,但让它在这里):

@app.route("/wifi", methods=["GET", "POST"])
@flask_login.login_required
def wifi():
    # something here
        if request.method == 'POST':
            start_date = request.form["calendar1"]
            end_date = request.form["calendar2"]
            period = request.form["period"]
            # do some work
    return render_template("wifi.html", result_dict=result_dict, wifipic="wifi" + pic_end)

标签: pythonjqueryhtmlgoogle-chromeflask

解决方案


因为你只能在提交事件中这样做

单击按钮时禁用按钮本身将停止提交表单

看来您的formtarget="{{url_for('wifi')}}" formmethod="post"也应该被删除。当您已经有表格时无需设置

在任何情况下,formtarget 都不是 URL - 您可能指的是 formaction

$("#wifi_form").on("submit",function() {
    if ($('#calendar1').val() && $('#calendar2').val()) {
      $("#loading").show();
      $("#content").hide();
      $(':input[type="submit"]').prop('disabled', true);
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="{{url_for('wifi')}}" class="ordinary_form" id="wifi_form">
  <label for="calendar1"> Choose time period start: </label>
  <input type="date" name="calendar1" id="calendar1" required> <br> <br>
  <label for="calendar2"> Choose time period end: </label>
  <input type="date" name="calendar2" id="calendar2" required></p>
  <label for="period"> Choose step: </label>
  <select required name="period" id="period">
    <option selected value="0">Day</option>
    <option value="1">Week</option>
    <option value="2">Month</option>
  </select>
  <br><br>
  <input type="submit" value="Send" >
</form>


推荐阅读