Jq代码
<script type="text/javascript">
$(function () {
$("#btn1").click(function () {
$.getJSON("PersonHandler.ashx", function (data, status) { //data是返回值;status 请求状态success"、 "notmodified"
if (status == "success") { //返回数据成功
//jQuery.each(object, callback);指定需要遍历的对象或数组; callback指定的用于循环执行的函数。
$.each(data, function (index, item) { //遍历数据 index 是索引 item 是参数名
var beginTag = "<tr><td>";
var endTag = "</td></tr>";
var tag = "</td><td>";
$("#personBody").append($(beginTag + item.Name + tag + item.Age + tag + item.Gender + tag
+ item.Country + tag + item.Email + endTag));
});
}
});
});
});
</script>
用户信息类
/// <summary>
/// 包含用户的基本信息
/// </summary>
public class Person
{
/// <summary>
/// 获取或设置用户名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 获取或设置用户年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 获取或设置用户性别
/// </summary>
public string Gender { get; set; }
/// <summary>
/// 获取或设置用户国籍
/// </summary>
public string Country { get; set; }
/// <summary>
/// 获取或设置用户电子邮箱
/// </summary>
public string Email { get; set; }
}
返回用户集合的方法类
/// <summary>
/// 获取用户列表
/// </summary>
/// <returns>所有用户信息</returns>
public static List<Person> GetPersons()
{
List<Person> ps = new List<Person>(); //
Person p1 = new Person { Name = "Tom", Age = 32, Country = "US", Gender = "Male", Email = "tom@gmail.com" };
Person p2 = new Person { Name = "Jack", Age = 23, Country = "UK", Gender = "Male", Email = "jack@gmail.com" };
Person p3 = new Person { Name = "Eden", Age = 25, Country = "Canada", Gender = "Female", Email = "eden@gmail.com" };
Person p4 = new Person { Name = "Li Hua", Age = 29, Country = "China", Gender = "Male", Email = "lihui@163.com" };
Person p5 = new Person { Name = "Lvo", Age = 40, Country = "US", Gender = "Male", Email = "lvo@gmail.com" };
ps.Add(p1);
ps.Add(p2);
ps.Add(p3);
ps.Add(p4);
ps.Add(p5);
return ps; //返回list集合对象
}
一般处理程序
/// <summary>
/// 处理用户类的请求
/// </summary>
public class PersonHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
List<Person> persons = PersonRepository.GetPersons(); //创建person类型集合 = PersonRepository类下的GetPersons()方法 ;该方法返回一个Person集合
//用json.NET 转换格式
string json = JsonConvert.SerializeObject(persons); //把集合转化为json字符串
context.Response.Write(json); //输出字符串
}
public bool IsReusable
{
get
{
return false;
}
}
在利用js函数调用并解析