ajax - 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 保护。
谁能告诉我为什么我可能会收到一个空表格?
谢谢
解决方案
我相信您需要将标头放在包含 CSRF 令牌的 AJAX 请求中,就像这样
headers: {
"X-CSRFToken": "{{csrf_token()}}"
}
推荐阅读
- android-studio - 类没有实现 ActivityResultLauncher AS ArcticFox
- reactjs - 安装 react-redux@5.0.7 时遇到错误
- r - mtc.nodesplit error / Error in data[, "study"] == study : 未实现这些类型的比较
- android - FCM 通知在发布应用程序中不起作用
- django - 如何在 F 表达式中使用 jsonfield?
- python - Keras OCR 是否支持其他语言?
- java - 在运行 wildfly 的服务器(RHE7)上部署战争后出现 ClassNotFound 异常
- java - Firebase 远程配置不适用于 Google Play 上的实时版本
- php - php 中的 substr() 不索引过去的 '<' html 标签
- python - Pandas + BeautifulSoup - 如何在 for 循环下将数据添加到新列但同一行