我在嘗試將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來驗證用戶的輸入,從服務器的響應向我表明一切正常,但名和密碼的值undefinded我懷疑我的方法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();
也許我應該使用像$選擇器(「##NAME登錄表單」)?我試過了,它不起作用。請幫忙。
對於表單序列化你絕對正確。 我已經添加了這個變量 var queryString = $('#loginform')。formSerialize(); 並用它作爲我的數據,一切都很好。 我認爲,序列化數據已經存在。 感謝您的幫助。 – 2013-03-03 15:47:04