javascript - 如何在使用 AJAX 发送表单元素之前验证空白的表单元素?
问题描述
我正在尝试在使用 AJAX 请求发送表单元素之前对其进行验证。它检查错误,但表单被提交。
我的代码:
$('#accountFormAddEdit').on('submit', function(e){
e.preventDefault();
if($('#account').val() == "")
{
alert("Account name is required");
} else {
$.ajax({
url: '<?= base_url() ?>controller/method',
method: 'POST',
data: $('#accountFormAddEdit').serialize(),
beforeSend:function(){
$('#submit').val("Saving");
$('#accountForm').modal('hide');
},
success:function(data){
$('#accountFormAddEdit')[0].reset();
$('#accountForm').modal('hide');
},
dataType: 'JSON',
});
}
location.reload();
});
我正在使用 aHTML Modal
来显示表单 And PHP Codeigniter
。
当我提交表单location.reload()
时不会刷新页面,为了获得结果,我使用刷新页面。
那么如何检查空白并防止表单数据提交并在不刷新的情况下获得响应?
解决方案
如果没有值则返回 false,请使用以下函数:-
$('#accountFormAddEdit').on('submit', function(e){
e.preventDefault();
if($('#account').val() == ""){
alert("Account name is required");
return false;
} else {
$.ajax({
url: '<?= base_url() ?>controller/method',
method: 'POST',
dataType: 'JSON',
data: $('#accountFormAddEdit').serialize(),
beforeSend:function(){
$('#submit').val("Saving");
$('#accountForm').modal('hide');
},
success:function(data){
$('#accountFormAddEdit')[0].reset();
$('#accountForm').modal('hide');
location.reload();
},
});
}
});
推荐阅读
- python - Tkinter 文件对话框,传递文件路径并运行脚本的其余部分,转换为 .app
- java - MockMvc 空响应/返回
- angular8 - 如何在 Angular 8 中使用手机号码登录实现 Firebase?
- sqlite - 如果第一个选项卡在本地数据库中以反应原生方式插入数据,如何更新第二个选项卡?
- django - 如何将对象包含到类别或子类别中?
- excel - 使用 dic.MailMerge 循环不会保存我的文档。它会启动但不会停止,除非我将其关闭
- typescript - 尝试使用括号表示法访问对象属性时出现 Typescript 错误 TS1003
- jenkins - 端口地址已在使用:绑定
- selenium-webdriver - Cucumber Extent Report - 如何为每个黄瓜步骤添加屏幕截图
- javascript - jsPDF没有正确缩放html2canvas图像