问题描述
使用 JavaScript 检查表单提交,执行 ajax 调用以检查项目名称。如果响应为真(“项目名称存在”),那么我想取消提交表单并显示错误。
由于某种原因,阻止默认没有做任何事情来阻止页面的刷新或表单的提交。我每次测试都成功输入 if 语句,但是页面刷新并提交表单。
JS
$( document ).ready(function() {
// If the project entered already exists in our database,Cancel submission.
$('#add-project-form').on("submit",function(event){
console.log("SUBMITTING...");
let project_name = $('#project_ea').val();
$.ajax({
url: "api/Projects/ProjectExists/" + project_name,type: "POST",dataType: "json",success: function(data){
console.log(data);
console.log(event);
if (data == true){
//Prevent Submission of form
event.preventDefault();
console.log("Submission Halted.");
$('#project-name-error').show();
}
}
});
});
});
按钮被按下
<button type="submit" form="add-project-form" name="add-project-form-button" id="add-project-form-button" class="btn btn-primary">Save changes</button>
解决方法
在向 API 发送请求之前,您必须使用 event.preventDefault()。由于 API 调用是异步的,在成功方法中的 event.preventDefault() 执行之前,页面已经重新加载
编辑:您可以在事件处理程序开始时阻止默认并在数据为真时提交表单
$( document ).ready(function() {
// If the project entered already exists in our database,Cancel submission.
$('#add-project-form').on("submit",function(event){
event.preventDefault(); //prevents
console.log("SUBMITTING...");
let project_name = $('#project_ea').val();
$.ajax({
url: "api/Projects/ProjectExists/" + project_name,type: "POST",dataType: "json",success: function(data){
console.log(data);
console.log(event);
if (data == true){
//Prevent Submission of form
//event.preventDefault();
document.querySelector('#add-project-form').submit(); //you can submit the form using this function
console.log("Submission Halted.");
$('#project-name-error').show();
}
}
});
});
});