ASP.NET中利用JQuery AJAX修改用户密码
一、新建数据库,在项目App_Data右击,添加一个数据库,新建一个UserInfo表,表里设UserName,Password两个字段
二、新建一个Default.aspx页面,用表格简单布局,代码如下
<body> <form id="form1" runat="server"> <table> <tr> <td> 旧密码: </td> <td> <asp:TextBox ID="txtOldPass" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtOldPass">*</asp:RequiredFieldValidator><span id="msg"></span> </td> </tr> <tr> <td> 新密码: </td> <td> <asp:TextBox ID="txtNewPass" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtNewPass">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td> 确认新密码: </td> <td> <asp:TextBox ID="txtConfirmPass" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="RequiredFieldValidator" Display="Dynamic" ControlToValidate="txtConfirmPass">*</asp:RequiredFieldValidator><asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToCompare="txtNewPass" ControlToValidate="txtConfirmPass">两次密码不一致</asp:CompareValidator> </td> </tr> <tr> <td colspan="2" align="center"> <asp:Button ID="btnModify" runat="server" Text="修改" /> </td> </tr> </table> </form> </body>
三、新建一个WebService,名为:CheckPassword.asmx,注意将 [System.Web.Script.Services.ScriptService]这个取消注释
代码如下:
/// <summary> /// CheckPassword 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService] public class CheckPassword : System.Web.Services.WebService { [WebMethod] public string IsCorrectPass(string username, string password) { string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; string word = ""; using (SqlConnection conn = new SqlConnection(connStr)) { using (SqlCommand cmd = new SqlCommand(string.Format("select password from UserInfo where UserName='{0}'", username), conn)) { conn.Open(); word = cmd.ExecuteScalar().ToString(); if (word == password) { return "密码正确"; } else { return "密码错误"; } } } } }
四、Default.aspx页面里加入以下JS代码
<script type="text/javascript"> $(function() { $("#<%=txtOldPass.ClientID %>").blur(function() { $.ajax({ type: "POST", contentType: "application/json", url: "CheckPassword.asmx/IsCorrectPass", data: "{username:'admin',password:'" + $(this).val() + "'}", //这里为了方便用户名就只有一个, dataType: "json", //数据库里也就一条数据 success: function(result) { $("#msg").text(result.d); } }); }); }); </script>
其实很简单,就是练习JQuery AJAX,作为刚刚学习JQuery的我,就当是练笔吧。
五、最后的运行效果为
作为练习没有实现加密,密码也直接显示出来了。当输入正确的密码,然后光标离开文本框就立即判断密码输入是否正确。