日期:2014-05-17  浏览次数:21370 次

asp.net JSON实例

1、创建一个一般处理程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace TestAjax
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class jSonTest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");

            JavaScriptSerializer jss = new JavaScriptSerializer();
            string json= jss.Serialize(new Person() { Name = "liyang", Age = 25 });
            json=   jss.Serialize(new string[] {"核武器","好" });
            Person[] persons = new Person[] { 
                new Person(){Name ="liyang",Age=25},
                new Person(){Name="lisi",Age=20},
                new Person(){Name="xiaopihai",Age= 5}
            };
            json = jss.Serialize(persons);
            context.Response.Write(json);


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }

        }
        

        

    }
}


2、前台页面调用 这里用的是jquery    jquery-1.7.2.js 自己下载吧

<!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>
    <title></title>

    <script src="js/jquery-1.7.2-vsdoc.js" type="text/javascript"></script>

    <script src="js/jquery-1.7.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function() {
            $.post("jsonTest.ashx", function(data, status) {
                //alert(data+"_"+status);
                alert(data);
                var person = $.parseJSON(data);
                alert(person.Name+"_"+person["Name"]+"_"+person["核武器"]);
            });
        });
    
    
    </script>
    
</head>
<body>



</body>
</html>