我注意到我的请求被解雇了两次,但我不明白为什么。
我有一个简单的表格:
<form method="POST" class="mb-4" autocomplete="off" action="/recipe/add" novalidate id="form">
<div class="form-group">
<label for="title">Rezeptname</label>
<input required type="text" name="title" id="title" class="form-control form-control-sm needs-validation" value="">
<div class="invalid-feedback">Ein Name wird für das Rezept benötigt!</div>
</div>
<div class="form-group">
<label for="cookingTime">Zubereitungsdauer in Minuten</label>
<input type="number" name="cookingTime" id="cookingTime" class="form-control form-control-sm" value="">
</div>
<div class="form-group">
<label for="servings">Portionen</label>
<input type="number" name="servings" id="servings" class="form-control form-control-sm" value="">
</div>
<label for="ingredients">Zutaten</label>
<button class="btn btn-outline-secondary btn-sm ml-2" onclick="createInputRow()"><i class="fas fa-plus"></i></button>
<div class="mb-4" name="ingredients">
<table class="table">
<tbody id="tbody">
</tbody>
</table>
</div>
<button type="submit" class="btn btn-primary btn-sm" id="submit">Speichern</button>
<a href="javascript:history.back()" class="btn btn-secondary btn-sm">Zurück</a>
</form>
在文档加载时,我为按钮添加了事件监听器
$(document).ready(() => {
$("#submit").unbind("click").bind("click", event => {
onSubmit(event)
})
})
在onSubmit方法中,发送请求:
$.ajax({
type: "POST",
url: "/recipe/add",
data: {recipe: recipeData},
success: (res) => {
console.log(JSON.parse(res))
}
});
这导致我的服务器上出现错误。 但是,在前端设置断点时,它只会触发一次。后端收到两个请求,就像在网络扫描中一样。
我已经尝试了$(“#submit”)。unbind()。bind(),如其他资料所述,但这并不能解决问题。
答案 0 :(得分:2)
如果您要将<form>
标记用于其他目的(包括重定向),则应将type=submit
从提交按钮中删除,或者使用preventDefault()
来防止默认的表单操作。另请注意,如果在文本字段中,按“ Enter”键也可能会提交表单。您也可以使用preventDefault()
来防止在此操作期间提交表单。