我正在尝试使用Ajax请求将表单提交到我的asp.net之前验证我的表单。我是Jquery Ajax的新手。请任何人帮助我。谢谢。
$(document).ready(function () {
$("#btnSubmit").click(function () {
var data = {
details: {
GroupName: $("#txtGroupName").val(),
Description: $("#txtDescription").val(),
}
};
$('#form1').validate({
rules: {
"txtGroupName": {
required: true,
minlength: 5
},
"txtDescription": {
required: true,
minlength: 5
}
},
messages: {
"txtGroupName": {
required: "You must enter your group name",
minlength: "group name must be at least 5 characters long"
},
"txtDescription": {
required: "You must enter your Description",
minlength: "Description must be at least 5 characters long"
}
},
submitHandler: function (form) {
$.ajax({
url: "AddGroup.aspx/SaveData",
data: JSON.stringify(data),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.d);
},
error: function (xhr, ajaxxOptions, thrownError) {
alert(thrownError);
}
});
$("#txtGroupName").val("");
$("#txtDescription").val("");
}
});
});
});
我的html页面看起来
<form id="form1" runat="server">
<div>
<input id="txtGroupName" type="text" runat="server" name="txtGroupName" placeholder="Group Name"/>
</div>
<div>
<textarea id="txtDescription" name="txtDescription" runat="server" placeholder="Description"></textarea>
</div>
<input id="btnSubmit" type="button" value="Submit" />
<input id="btnLoad" type="button" value="Load Data" />
</form>
答案 0 :(得分:0)
你很亲密。但是,您将 NOT 将.validate()
方法放在任何类型的click
处理程序中。 .validate()
方法仅 用于初始化插件,插件会自动捕获click
事件。
$(document).ready(function () {
$('#form1').validate({
rules: {
"txtGroupName": {
required: true,
minlength: 5
},
"txtDescription": {
required: true,
minlength: 5
}
},
messages: {
"txtGroupName": {
required: "You must enter your group name",
minlength: "group name must be at least 5 characters long"
},
"txtDescription": {
required: "You must enter your Description",
minlength: "Description must be at least 5 characters long"
}
},
submitHandler: function (form) {
var data = { ... };
$.ajax({
....
});
$("#txtGroupName").val("");
$("#txtDescription").val("");
}
});
});