在表单验证器中调用 $.ajax
Calling $.ajax inside form validator
如何在 jQuery 验证的 submitHandler()
中编写 $.ajax()
调用?下面是我的代码。我只有一个文本 Empname
.
$('#FormSubmit').validate({
rules: {
EmpName: {
required: true,
minlength: 5,
maxlength: 10
},
meassages: {
EmpName: {
required: function() {
return $('#lblName').text('Name Req min2 max15');
}
submitHandler: function(FormSubmit) {
$.ajax({
url: "http://localhost:10948/Api/Home/PostData",
method: "POST",
contentType: 'application/x-www-form-urlencoded',
success: function() {
}
})
},
<form id="FormSubmit" method="post">
<div class="form-horizontal">
<div class="form-group">
<b>EmpName</b><input type="text" name="EmpName" required />
<span id="lblName"></span>
</div>
</div>
<input type="submit" value="Submit" />
</form>
它没有处理我的 url
并且还给我一个错误:
HTTP Error 405.0 - Method Not Allowed
首先请注意您有几个语法问题,例如没有正确关闭对象,messages
键入错误以及 required
消息需要 return 字符串值。
其次,submitHandler
只是一个在表单有效时执行的函数。您需要将实际的 $.ajax
逻辑放入其中,而不仅仅是请求参数:
$('#FormSubmit').validate({
rules: {
EmpName: {
required: true,
minlength: 5,
maxlength: 10
}
},
messages: {
EmpName: {
required: 'Name Req min2 max15'
}
},
submitHandler: function(form) {
$.ajax({
url: "http://localhost:10948/Api/Home/PostData",
method: "POST",
data: $(form).serialize(),
success: function(response) {
console.log('it worked!');
console.log(response);
}
});
}
});
如何在 jQuery 验证的 submitHandler()
中编写 $.ajax()
调用?下面是我的代码。我只有一个文本 Empname
.
$('#FormSubmit').validate({
rules: {
EmpName: {
required: true,
minlength: 5,
maxlength: 10
},
meassages: {
EmpName: {
required: function() {
return $('#lblName').text('Name Req min2 max15');
}
submitHandler: function(FormSubmit) {
$.ajax({
url: "http://localhost:10948/Api/Home/PostData",
method: "POST",
contentType: 'application/x-www-form-urlencoded',
success: function() {
}
})
},
<form id="FormSubmit" method="post">
<div class="form-horizontal">
<div class="form-group">
<b>EmpName</b><input type="text" name="EmpName" required />
<span id="lblName"></span>
</div>
</div>
<input type="submit" value="Submit" />
</form>
它没有处理我的 url
并且还给我一个错误:
HTTP Error 405.0 - Method Not Allowed
首先请注意您有几个语法问题,例如没有正确关闭对象,messages
键入错误以及 required
消息需要 return 字符串值。
其次,submitHandler
只是一个在表单有效时执行的函数。您需要将实际的 $.ajax
逻辑放入其中,而不仅仅是请求参数:
$('#FormSubmit').validate({
rules: {
EmpName: {
required: true,
minlength: 5,
maxlength: 10
}
},
messages: {
EmpName: {
required: 'Name Req min2 max15'
}
},
submitHandler: function(form) {
$.ajax({
url: "http://localhost:10948/Api/Home/PostData",
method: "POST",
data: $(form).serialize(),
success: function(response) {
console.log('it worked!');
console.log(response);
}
});
}
});