preventDefault()无法阻止提交表单



使用JavaScript检查表单的提交,执行ajax调用以检查项目名称。如果响应为真("项目名称存在"(,那么我想取消提交表单并显示错误。

由于某些原因,prevent Default没有采取任何措施来阻止刷新页面或提交表单。每次测试时,我都成功地输入了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.prventDefault((。由于API调用是异步的,在成功方法中的event.prventDefault((执行之前,页面已经被重新加载

编辑:您可以在事件处理程序开始时防止默认,并在数据为真实时提交表单

$( 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();
}  
}
}); 
});

});

最新更新