首页 > 解决方案 > 为什么我的表单不使用 ajax 和烧瓶 wtforms 提交到后端?

问题描述

我有一个提交费用的功能,我希望它在提交时不要重新加载页面。我尝试使用 ajax,但即使没有错误也没有提交表单。

add_expense.html

<div class="popup">
            <div class="popup-content">
                <i class="far fa-times-circle close"></i>
                <form action="" method="POST">
                    {{ form.csrf_token }}
                    <div class="table-input">
                        <div class="expense-form">
                            <div class="categories">
                                {{ form.categories.label }}
                                {{ form.categories(class="add-categories", id="category") }}
                            </div>
                            <div class="cost">
                                {{ form.cost.label }}
                                {{ form.cost(class="add-cost", id="cost") }}
                            </div>
                            <div class="submit">
                                {{ form.submit(class="add-expense") }}
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var csrf_token = "{{ csrf_token() }}";
    </script>
    <script src="{{ url_for('static', filename='js/add_expense.js')}}"></script>

add_expense.js:

$(function() {
    $('form').on('submit', function(event) {
        event.preventDefault();
        var budget_id = window.location.href
        var splits = budget_id.split('/')
        var id = (splits[splits.length-1])
        $.ajax({
            data : {
                category: $('#category').val(),
                cost: $('#cost').val()
            },
            type: 'POST',
            url: id,
            success: function() {
                alert('success')
            }
        })
    })

})

 $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrf_token);
            }
        }
    });

我在我的init .py中包含了 CSRFProtect

警报功能正在运行,但未提交到后端。我尝试搜索答案,但我总是找到相同的方法。谁能帮助它为什么不提交?

标签: javascriptajaxflask-wtforms

解决方案


推荐阅读