javascript - 如何验证表单然后发出一个 post http 请求 jQuery
问题描述
我正在尝试验证我的表格。例如,当用户没有输入任何值或空格时,jQuery 验证插件会检测到错误并显示一个错误消息,称为“请填写该字段”或“没有空格”。如果验证正确,将在 jQuery ajax 的帮助下发出一个 post HTTP 请求,将信息发送到服务器。目前,当用户单击提交时,我能够验证但无法发出 post HTTP 请求。这是我的代码
<script>
function WebFormData(inLessonName) {
this.lessonName = inLessonName;
}
$('#dataForm').validate({
rules: {
lessonName: {
required: true,
nowhitespace: true
}
},
submitHandler: function (form) {
var collectedLessonName = $('#lessonName').val();
var webFormData = new WebFormData(collectedLessonName);
var webFormDataInString = JSON.stringify(webFormData);
$saveSessionSynopsisDataHandler = $.ajax({
method: 'POST',
url: '/API/Session',
dataType: 'json',
contentType: 'application/json;',
data: "'" + webFormDataInString + "'"
});
}
});
</script>
<form id="dataForm" role="form" class="form-horizontal">
<label class="control-label col-md-4" for="lessonName">lesson name</label>
<input type="text" id="lessonName" name="lessonName" class="form-control font-bold"
maxlength="100" placeholder="lessonName" value="" />
<div class="col-md-10">
<div class="pull-right">
<input type="button" class="btn btn-primary" value="Save" id="saveButton" />
</div>
</div>
</form>
解决方案
使用调用函数的onsubmit
方法。form
如果返回false
则不提交,如果是true
,则表单提交。只需将我的示例添加到您的 jquery 中即可
function validation(){
// check whatever you want to check here, return false if there is an error like white space
if (document.getElementById("name").value.length < 1) {
window.alert("fill the field");
return false; // form not submited
} else {
// if everything is fine then you can submit
return true;
}
}
<form onsubmit="return validation()">
Name: <input type="text" name="fname" id="name">
<input type="submit" value="Submit">
</form>
推荐阅读
- php - 无法发布在循环中创建的多个复选框的值
- c# - 获取具有特定列的最小整数值的datagridview行的索引的最佳方法是什么
- c++ - 将 std::any 转换回其原始类型?
- python - 输出不是我预期的
- ethereum - Go-Ethereum 自定义网络:如何限制合约创建?
- sql-server - 从不同版本的 SQL Server 还原 SQL Server 数据库时遇到问题
- c++ - Custom class iterator following a list of integer indices?
- mysql - How to assign aliases to an array of column names with Joomla's quoteName()?
- reactjs - React Component 在我的状态下没有收到我的道具
- r - ggplot geom_boxplot 中间 aes 没有效果