简单实现了通过jQuery的Ajax函数异步请求一般处理程序,数据由list模拟,返回json格式的数据。
index.html:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="js/jquery.min.js" type="text/javascript"></script> <script> $(function () { $.ajax({ type: "POST", url: "Handler2.ashx", eache: false, datatype: "json", success: function (data) { var obj = eval(data); $(obj).each(function (index) { var val = obj[index]; $("body").append("<div class=‘show‘>" + val.Id + " " + val.Name + " " + val.Pwd + "</div>"); }); }, error: function () { return; } }); }); </script> </head> <body> </body> </html>
Handler.ashx
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; Model model1 = new Model(); Model model2 = new Model(); model1.Id = "c00001"; model1.Name = "张三"; model1.Pwd = "123456"; model2.Id = "c00002"; model2.Name = "李四"; model2.Pwd = "123456"; List<Model> list = new List<Model>(); list.Add(model1); list.Add(model2); try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(list.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, list); context.Response.Write(Encoding.UTF8.GetString(ms.ToArray())); } } catch { return; } }
时间: 2024-10-06 21:31:02