简单的使用json小例子

基本实现功能,就是在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; }
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值