常规的Jquery Ajax 验证登录,主要有3种服务端页面相应 ,也就是 aspx,ashx,asmx即webserivice 。
下面分别用3种方式来(aspx,ashx,asmx)做服务端来处理 Jquery Ajax 传过来的用户名和密码验证!
例: Login.html 请求用户名和密码验证!
1.服务端为 AjaxLogin.aspx 页面
首先修改 $.ajax 的 Url:"AjaxLogin.aspx"
protected void Page_Load(object sender, EventArgs e) { if (Request.Form["name"] != null && Request.Form["pwd"] != null) { if (Request.Form["name"].ToString().Trim() != "" && Request.Form["pwd"].ToString() != "") { string name = Request.Form["name"].ToString().Trim(); string pwd = Request.Form["pwd"].ToString(); Response.Cookies.Clear(); Response.Cookies.Add(new HttpCookie("name", name)); //添加cookie Response.Cookies.Add(new HttpCookie("pwd",pwd));//添加密码 Response.Write("你已经成功登录"); } } }
2. 服务端为 AjaxLoginAshx.ashx 页面 (一般处理程序)
首先修改 $.ajax 的 Url:"AjaxLoginAshx.ashx"; 另:ashx以context.Response.Write 返回内容
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class AjaxLoginAshx : IHttpHandler { public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); if (context.Request.Form["name"] != null && context.Request.Form["pwd"] != null) { if (context.Request.Form["name"].ToString().Trim() != "" && context.Request.Form["pwd"].ToString() != "") { string name = context.Request.Form["name"].ToString().Trim(); string pwd = context.Request.Form["pwd"].ToString(); context.Response.Cookies.Clear(); context.Response.Cookies.Add(new HttpCookie("name", name)); context.Response.Cookies.Add(new HttpCookie("pwd", pwd)); context.Response.Write("你已经成功登录"); } else { context.Response.Write("没成功登录1"); } } else { context.Response.Write("没成功登录2"); } } public bool IsReusable { get { return false; } }
3. 服务端为 AjaxLoginAsmx.asmx页面 (SOAP方式HTTP访问,用XML返回)
首先修改 $.ajax 的 Url:"AjaxLoginAsmx.asmx/login"; 注意: / 后面是方法名
另asmx页面以return 返回内容,response.cookies.add添加cookie
////// AjaxLoginAsmx 的摘要说明 /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class AjaxLoginAsmx : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string login() { if (HttpContext.Current.Request.Form["name"] != null && HttpContext.Current.Request.Form["pwd"] != null) { if (HttpContext.Current.Request.Form["name"].ToString().Trim() != "" && HttpContext.Current.Request.Form["pwd"].ToString() != "") { string name = HttpContext.Current.Request.Form["name"].ToString().Trim(); string pwd = HttpContext.Current.Request.Form["pwd"].ToString(); //HttpContext.Current.Response.Cookies.Add(new HttpCookie("name", name)); //HttpContext.Current.Response.Cookies.Add(new HttpCookie("pwd", pwd)); //HttpContext.Current.Response.Write("你已经成功登录"); HttpContext.Current.Response.Cookies.Add(new HttpCookie("a", "123")); return "Hello World"; } else { return "error1"; } } else { return "error2"; } }