先直接上一个简单的实例:
aspx页面:

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Ajax简单实例</title> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(function () { $("#btnAjax").click(function () { $.post("Ajax.ashx?action=Show", { ID: "2012" }, function (data) { var json = eval("(" + data + ")"); //对返回的json数组进行解析 alert(json.ID); }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="Ajax" id="btnAjax" /> </div> </form> </body> </html>
ajax.ashx:

public class ajax : IHttpHandler { public void ProcessRequest(HttpContext context) { string action = context.Request.QueryString["action"]; switch (action) { case "Show": Show(); break; } } protected static void Show() { System.Threading.Thread.Sleep(3000); string ID = HttpContext.Current.Request["ID"]; WriteJson("ID", ID); } /// <summary> /// 输出Json /// </summary> /// <param name="key"></param> /// <param name="val"></param> private static void WriteJson(string key, string val) { HttpContext.Current.Response.Write(GetJSON(key, val)); HttpContext.Current.Response.ContentType = "text/plain"; //设置MIME格式 HttpContext.Current.Response.End(); } /// <summary> /// 获取JSON字符串 /// </summary> /// <param name="dic"></param> /// <returns></returns> private static string GetJSON(string key, string val) { return string.Format("{{\"{0}\":\"{1}\"}}", key, val); } public bool IsReusable { get { return false; } }
有几点要说明
1 根据获取action的值来确定调用使用哪个方法
2.将方法返回的值格式化为json格式
3 当$.post的回调函数接受返回的json字符串必须先使用eval解析,在对字符串进行操作
下面上一个简单登陆的Ajax实,大体的代码和上面的实例一样
aspx

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Ajax简单实例-登陆</title> <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnLogin").click(function () { var name = $("#txtUserName").val(); var pwd = $("#txtPwd").val(); $.post("ajax.ashx?action=Login",{ username:name,password:pwd }, function (data) { var json = eval("(" + data + ")"); if (json.status == "1") { alert("登陆成功,正在跳转..."); //location.href = "";跳转 } else { alert("用户名或密码错误"); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <p><span>UserName:</span><input type="text" id="txtUserName" /></p> <p><span>PassWord:</span><input type="password" id="txtPwd" /></p> <p><input type="button" id="btnLogin" value="Ajax登陆" /></p> </div> </form> </body> </html>
ajax.ashx:

public class ajax : IHttpHandler { public void ProcessRequest(HttpContext context) { string action = context.Request.QueryString["action"]; switch (action) { case "Show": Show(); break; case "Login": Login();break; } } protected static void Login() { string strUserName = HttpContext.Current.Request["username"]; string strPwd = HttpContext.Current.Request["password"]; string status = string.Empty;//标识 if (strUserName == "admin" && strPwd == "123") { status = "1"; } else { status = "2"; } WriteJson("status", status); } protected static void Show() { string ID = HttpContext.Current.Request["ID"]; WriteJson("ID", ID); } /// <summary> /// 输出Json /// </summary> /// <param name="key"></param> /// <param name="val"></param> private static void WriteJson(string key, string val) { HttpContext.Current.Response.Write(GetJSON(key, val)); HttpContext.Current.Response.ContentType = "text/plain"; //设置MIME格式 HttpContext.Current.Response.End(); } /// <summary> /// 获取JSON字符串 /// </summary> /// <param name="dic"></param> /// <returns></returns> private static string GetJSON(string key, string val) { return string.Format("{{\"{0}\":\"{1}\"}}", key, val); } public bool IsReusable { get { return false; } }
当我们经常使用ajax的时候,可以对上面的代码进行封装
我简单的单独的写了一个ajax.js文件

/****************************************************************************** * filename: ajax.js *******************************************************************************/ var imgPath = "loading.gif"; //加载图片路径 var ajax = {}; //获取服务器路径 ajax.getPath = function (param) { return "ajax.ashx?action=" + param; }; //显示正在加载的图标 ajax.loading = function (src, show) { show = show || false; //显示 if (show) { $(src).after("<img id=\"loading\" src='" + imgPath + "' title='加载中...' alt='加载中...' />"); //$(src).hide(); } else { //隐藏 // $(src).show(); $("#loading").hide(); $(src).next().hide(); } }; var Tool = {}; //获取JSON数据 Tool.getJSON = function (str) { if (str == null || str == "") { return []; } return eval("(" + str + ")"); };
aspx页面:

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>封装方法</title> <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> <script type="text/javascript" src="ajax.js"></script> <script type="text/javascript"> $(function () { $("#AjaxTest").click(function () { ajax.loading(this, true); $.post(ajax.getPath("Show"), { ID: "2" }, function (data) { ajax.loading(this, false); var json = Tool.getJSON(data); alert(json.ID); }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" value="AjaxTest" id="AjaxTest" /><!--<img id="loading" src=loading.gif title='加载中...' alt='加载中...' />--> </div> </form> </body> </html>
还包括ajax.ashx文件
简单登陆的例子,也可以通过它来修改