• $.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;
            }
        }

    }

  • 相关阅读:
    IQuerable与IEnumable的区别
    idea2021.1新功能
    intellij idea2021快捷键大全
    解决报错:The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone.
    spring boot中不能识别RestController的原因
    Maven的安装与配置
    关于window10安装jdk,配置环境变量,javac不是内部或外部命令,也不是可运行的程序 或批处理文件的细节问题。
    记录日常工作经验,技术解决问题分享格式
    Brt课程设计day14
    Brt课程设计day13
  • 原文地址:https://www.cnblogs.com/mr-lee1976/p/4346753.html
Copyright © 2020-2023  润新知