如何在 jQuery validate 的 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
消息需要返回字符串值。
其次,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 - 在表单验证器中调用 $.ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47076508/