$.toJSON的用法或把数组转换成json类型

1. html页面全部代码

<html>
<head>
    <title></title>
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/JqueryJson.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#json").click(function () {

             //数组里的字段的命名和类型要和一般处理程序里定义的类里的变量要一样

             //否则会出问题
                var postdata = new Array();
                postdata[1] = { id: 1, number: "yes" };
                postdata[2] = { id: 2, number: "no" };

 

                var postData = $.toJSON(postdata);  //把数组转换成json字符串

                //将json字符串反序列化,这个只是测试一下数组是否转换成json字符串

                var content = $.parseJSON(postData);
                $.each(content, function () {
                    alert(this.number);
                });

                //post提交并处理

                $.post("json.ashx", { "array": postData }, function (data, status) {
                    if (status == "success") {
                        alert(data);
                    }
                });

            });
        })
    </script>
</head>
<body>
<input type="button" value="json" id="json"/>
</body>
</html>

2.json.ashx页面全部代码

<%@ WebHandler Language="C#" class="json" %>

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

public class json : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
               
        //接受出过来的值 

        string sun = context.Request["array"].ToString();

        //实例化JavaScriptSerializer对象
        JavaScriptSerializer jss = new JavaScriptSerializer();
        List<array> a = new List<array>();

        //把json转换其他list<array>类型
        a = jss.Deserialize(sun, typeof(List<array>)) as List<array>;
        string meg=null;
        foreach (var item in a)
        {
            meg += item.number;
        }
        context.Response.Write(meg);
    }

    public class array
    {
        public int id { get; set; }
        public string number { get; set; }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。