javascript - 为什么我的表单不使用 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
警报功能正在运行,但未提交到后端。我尝试搜索答案,但我总是找到相同的方法。谁能帮助它为什么不提交?
解决方案
推荐阅读
- mysql - 如何修复 global_priv mysql
- python - 这个字典理解代码有什么问题?
- c# - 如何在 C# 中创建多接口 com 类
- c - 当我们返回本地地址而不是本地变量时,为什么会产生运行时错误?
- java - 在 Android 中播放音频时出现故障
- perforce - 如何从 perforce 客户端“取消同步”文件?
- common-lisp - 与格式功能非常混淆
- elasticsearch - 无痛脚本错误 - “已达到可在循环中执行的最大语句数”
- angular - 除了 viewencapsulation.None 之外,是否有任何替代方案:host /deep/?
- python - 同一目录中所有罚款的 MD5 散列 - 错误没有这样的文件或目录