在尝试结合 jQuery 验证(插件)和使用 ajax 将数据发送到服务器时,我遇到了以下问题。
如果我使用此 jQuery 方法仅将数据单独发布到服务器,则一切正常。
function doAjaxPost() {
// get the form values
var name = $('#name').val();
var pswd = $('#pswd').val();
$.ajax({
type: "POST",
url: "${pageContext. request. contextPath}/loginUser.htm",
data: "name=" + name + "&pswd=" + pswd,
success: function(response){
// we have the response
if(response.status == "OK") {
$('#info').html("User has been added to the list successfully.<br>"+
"The User Details are as follows : <br> Name : "+
response.result.name + " <br> Password: " + response.result.pswd);
$('#name').val('');
$('#pswd').val('');
} else {
$('#info').html("Sorry, there is something wrong with the data provided")
}
},
error: function(e){
alert('Error: ' + e);
}
});
}// end of doAjaxPost
但是当我尝试使用 jquery.validate.min.js 验证用户的输入时,服务器的响应显示一切正常,但名称和密码的值未定义我怀疑我的方法 doAjaxPost() 失败在 jquery.validator 之后从表单中提取数据。这是我的验证功能:
$(document).ready(function(){
$("#loginform").validate({
submitHandler: function(form) {
doAjaxPost();
},
rules:{
name:{
required: true,
minlength: 4,
maxlength: 16,
},
pswd:{
required: true,
minlength: 6,
maxlength: 16,
},
},
messages:{
name:{
required: "Login - is a mandatory field",
minlength: "Name should contain minimum {0} symbols",
maxlength: "Maximum symbols - {0}",
},
pswd:{
required: "Password - is a mandatory field",
minlength: "Password should contain minimum {0} symbols",
maxlength: "Password should contain maximum {0} symbols",
},
},
});
});
所以我的问题是如何从经过验证的表单中提取数据并将其传递给 doAjaxPost 函数?
因为我认为这些变量从表格中得不到任何东西
var name = $('#name').val();
var pswd = $('#pswd').val();
也许我应该使用像 $('#loginform #name') 这样的选择器?我试过了,它不起作用。请帮忙。