基本实现功能,就是在html页面,通过ajax请求,返回json格式的数据,然后再html页面取出这些数据,展示在table上。
html页面的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <title>简单使用json小例子</title> <script type="text/javascript"> $(function () { $("#btnGet").click(function () { $.ajax({ type: "get", url: "../ajax/json1.aspx", dataType: "text", success: function (data, textstatus) { var datas = eval(data);//通过eval函数,把字符串转换为对象 var htmlContent = "<tr><td>姓名</td><td>年龄</td><td>性别</td><td>地址</td></tr>"; $.each(datas, function (personIndex, Person) { htmlContent += "<tr><td>" + Person["Name"] + "</td><td>" + Person["Age"] + "</td><td>" + Person["Sex"] + "</td><td>" + Person["Address"] + "</td></tr>"; }); $("#tableContent").html(htmlContent); } }); }); }) </script> </head> <body> <div> <input type="button" id="btnGet" value="获取"/> <table id="tableContent" width="800px;"> </table> </div> </body> </html> 通过ajax请求到一个.aspx页面;
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using WebApplication1.model; namespace WebApplication1.ajax { public partial class json1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { List<Person> list = new List<Person>(); for (int i = 0; i < 10; i++) { Person p = new Person(); p.Name = "罗"+i; p.Age = i; p.Sex = "girl"+i; p.Address = "上海市万航渡路888号"+i; list.Add(p); } Response.ContentType = "text/plain"; string str = @"[{Name:'" + list[0].Name + "',Age:" + list[0].Age + ",Sex:'" + list[0].Sex + "',Address:'" + list[0].Address + "'}"; str+=" ,{Name:'"+list[1].Name+"',Age:"+list[1].Age+",Sex:'"+list[1].Sex+"',Address:'"+list[1].Address+"'}]"; Response.Write(str); } } } 定义了一个Person对象 public class Person { public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } public string Address { get; set; } }