首页 > 解决方案 > 表单提交被 Javascript 忽略,但被 Flask 拾取

问题描述

我的 Flask 应用程序中有一个表单。我需要通过 Javascript (JS) 调解表单提交。期望的行为是,在提交表单时,我们会立即获得重定向,然后 JS 与 Flask 对话,Flask 发送响应,JS 更新 DOM。

问题:表单没有提交给 JS。提交时,输入框中的文本会被清除,页面就在那里。没有错误记录到控制台

它似乎忽略了我的 JS,虽然<script>标签是有序的,它们的位置layout.html是正确http://localhost:5000/static/index.js的,并显示文件。我插入了一条console.log语句来测试是否触发了适当的 JS 函数。一无所获。我将所有内容都包含在$(document).ready(). 依然没有。method="post"<form>标签中放置一个属性,name在表单的input框中放置一个属性允许我直接提交给 Flask,但我需要它去 JS。所有这些都在我的机器上播放,所以没有 CORS。我哪里错了?

必须先到 JS 再到 Flask 的表单

<div class="container">
    <div class="display-3">
        <strong>Create A Channel</strong>
    </div>
    <form id="channelForm" class="mt-4">
        <label for="channelName">Channel Name</label>
        <input id="channelName" class="form-control" type="text" placeholder="Enter Channel Name">
      <input type="submit" class="btn btn-primary" value="Create Channel">
    </form>
</div>

缩写JS

document.querySelector('#channelForm').onsubmit = () => {
    console.log("here");
    window.location.href = 'messages.html';

    // other stuff that links to Flask route

};

烧瓶路线

@app.route('/channels', methods=["GET", "POST"])
def channels():
    channelList = []
    if request.method == "POST":

        channel = request.form.get("channel")

        if not (channel is None) and not (channel in channelList):
            channelList.append(channel)
            print(channelList)
            return jsonify({"success": True, "channel":channelList})
        else:
            return jsonify({"success": False})

    else:
        return render_template("channels.html")

来自 layout.html 的头部

<head>
    {% block head %}
    <!-- Bootstrap 4 -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
    <!-- Additional CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    <!-- JS -->
    <script src="{{ url_for('static', filename='index.js') }}"></script>
    {% endblock %}
</head>

编辑 当我点击按钮提交表单时,我"GET /static/index.js HTTP/1.1" 200 -在终端中看到。控制台中仍然没有任何内容,但我认为 GET 请求不寻常,因为我正在点击按钮提交表单。期待POST。

标签: javascripthtmlflask

解决方案


问题是您的表单是通过 HTTP 协议(​​传统表单提交)而不是 JS 提交的。为防止这种情况,您需要停止单击按钮提交表单:

var form = document.querySelector('#channelForm'),
    button = form.querySelector('input.btn-primary');

button.addEventListener('click', function(e) {
  e.preventDefault();
  console.log('process form data!');
})

此外,将您的 JavaScript 包含放在您的 HTML 包含之后,以便您的 JS 所针对的元素在 JS 加载时位于页面上。


推荐阅读