首页 > 解决方案 > Flask Ajax 帖子返回 TypeError:'NoneType' 对象不可迭代用于表单数据

问题描述

我已经看到了多个关于如何使用 wtf-forms 在烧瓶中实现 ajax post 方法的问题,并且我已经阅读了文档。我以这篇文章为例,但我收到一个 TypeError: 'NoneType' object is not iterable。我已经验证了不使用 ajax 的表单数据,一切正常。我不确定为什么它不适用于 ajax 请求。

我的表格:

class PathsForm(FlaskForm):
    name = StringField('Name', validators = [DataRequired()])
    paths = SelectField('Path')
    cbt_id = HiddenField('CBT ID', validators = [DataRequired()])

我的模板:

{% extends "base.html" %}

{% block content %}
    <h1>Edit {{ cbt.name }} </h1>
    <form action="" method="post">
        {{ form.hidden_tag() }}
    <table>
        <tr>
            <th>{{ form.name.label }}</th>
            <th>{{ form.paths.label }}</th>
        <tr>
            <td>{{ form.name(size=32) }}</td>
            <td>{{ form.paths() }}</td>
        </tr>
    </table>
    {{ form.cbt_id() }}
    <input type = "submit" value = "Add Path"/>
    </form>

    <script type="text/javascript">

    $(document).ready(function() {
        $('form').submit(function (e) {
            var url = "{{ url_for('process_cbt') }}"; // send the form data here.
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: $('form').serialize(),// serializes the form's elements.
                success: function (data) {
                    console.log(data)  // display the returned data in the console.
                }
            });
            e.preventDefault(); // block the traditional submission of the form.
        });
        // Inject our CSRF token into our AJAX request.
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ form.csrf_token._value() }}")
                }
            }
        })
    });
    </script>
{% endblock %}

我的烧瓶路线:

@app.route('/process_cbt', methods = ['POST'])
@login_required
def process_cbt():
    form = PathsForm()
    if form.validate_on_submit():
        return jsonify(data={'message':'Success'})
    return jsonify(data={'message': 'Failure'})

看起来 csrf 令牌已正确实施,我已按照文档设置 CSRF 保护。

谁能告诉我为什么我可能会收到一个空表格?

谢谢

标签: ajaxformsflaskcsrfflask-wtforms

解决方案


我相信您需要将标头放在包含 CSRF 令牌的 AJAX 请求中,就像这样

                      headers: {

                        "X-CSRFToken": "{{csrf_token()}}"
                      }

推荐阅读