一、使用HttpHandler实现服务器代码:
<%@ WebHandler Language="C#" Class="RegisterAjax" %> using System; using System.Web; using BookShopBLL; using BookShopModels; public class RegisterAjax : IHttpHandler { public void ProcessRequest (HttpContext context) { try { string mess = ""; context.Response.ContentType = "text/plain"; Users user = new Users(); //获取用户名,注意这里使用Request.Form[] user.LoginId=context.Request.Form["loginId"].ToString(); //获取密码,注意这里使用Request.Form[] user.LoginPwd = context.Request.Form["loginPwd"].ToString(); user.Name = context.Request.Form["name"].ToString(); user.Address = context.Request.Form["address"].ToString(); user.Phone = context.Request.Form["phone"].ToString(); user.Mail = context.Request.Form["mail"].ToString(); UserRoles ur = new UserRoles(); ur.Id = 2;//会员 UserStates us = new UserStates(); us.Id = 1;//1.正常 2.无效 user.UserRole = ur; user.UserState = us; if (UserManager.Add(user)) { mess = "注册成功!"; } else { mess = "注册失败!"; } context.Response.Write(mess); } catch (Exception) { context.Response.Write("注册失败!"); } } public bool IsReusable { get { return false; } } }
二、页面 javascript 代码:
<script language ="javascript" type="text/javascript" > function CreateXmlHttpRequest() { if (window.ActiveXObject) {//如果是IE浏览器 return new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) {//非IE浏览器 return new XMLHttpRequest(); } } function registerUser() { //请求字符串 var url = "ajaxHandler/RegisterAjax.ashx"; //获取表单数据 var loginId = document.getElementById('<%=txtLoginId.ClientID %>').value; var name = document.getElementById('<%=txtName1.ClientID %>').value; var loginPwd = document.getElementById('<%=txtLoginPwd.ClientID %>').value; var email = document.getElementById('<%=txtEmail.ClientID %>').value; var address = document.getElementById('<%=txtAddress.ClientID %>').value; var phone = document.getElementById('<%=txtTele.ClientID %>').value; //拼接信息字符串,escape()方法用来对字符串进行编码 var userInfo = "loginId=" + escape(loginId) + "&name=" + escape(name) + "&loginPwd=" + loginPwd + "&address=" + address + "&phone=" + phone + "&mail=" + email; var xhr = CreateXmlHttpRequest();//创建XmlHttpRequest对象 //设置回调函数 xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); //提示信息 } }; xhr.open("POST",url,true); //使用post //setRequestHeader()用来设置请求的头部信息,Content-Type表示内容类型 //这里将Content-Type设置为application/x-www-form-urlencoded,表示发送的数据为表单数据, //这样在服务器端才可以使用Request.Form[]获取到提交的数据。 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //发送请求 xhr.send(userInfo); }
html提交按钮代码:
<asp:Button ID="btnRegister" OnClick="btnSubmit_Click" OnClientClick="registerUser(this);return false;" runat="server" Text="确定了,马上提交" CssClass="opt_sub"></asp:Button>
OnClientClick="registerUser(this);returnfalse;"中的returnfalse表示不执行服务器端的提交方法。