Jquery重新学习之五[操作JSON数据]

Jquery操作Json格式的数据在我们平时的项目中也经常运用;最近看Jquery权威指南中就有一章节是对这方面的整理总结;最后通过一个Asp.net结合一般处理程序ashx的实例,基本上能满足项目中平时遇到的问题;

1:Json格式在JS中直接通过"对象.属性名称"就可以进行访问;

<head>
    <title>jQuery 读取JSON 数据</title>
    <script src="JScript/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var objInfo = {
            ‘name‘: ‘踏浪帅‘,
            ‘sex‘: ‘男‘,
            ‘Age‘: ‘20‘
        };
        $(function() {
            $("#Button1").click(function() {
                var strHTML = "";
                strHTML += "姓名:" + objInfo.name + "<br>";
                strHTML += "性别:" + objInfo.sex + "<br>";
                strHTML += "年龄:" + objInfo.email + "<hr>";
                $("#Tip").html(strHTML);
            }); ;
        });
    </script>
</head>
<body>
   <div class="iframe">
         <div class="title">
              <input id="Button1" type="button"
                     class="btn" value="获取数据" />
         </div>
         <div class="content">
              <div id="Tip"></div>
         </div>
    </div>
</body>
</html>

 

2:在前端JS字符串转化成JSON格式是通过eval()进行;

<head>
    <title>jQuery 操作JSON 数据</title>
    <script src="JScript/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var strInfo = "{‘name‘: ‘小明‘,‘sex‘: ‘男‘,‘email‘: ‘[email protected]‘,‘date‘:1349340837359}";
        $(function() {
            var strV0 = "原始数据";
            var strV1 = "变化数据";
                var strHTML = "";
                //将字符串转成JSON对象
                var objInfo = eval(‘(‘ + strInfo + ‘)‘);
                //根据按钮文字改变JSON对象中的值
                if ($(this).val() == strV1) {
                    objInfo.date = new Date().getTime();
                }
                strHTML += "姓名:" + objInfo.name + "<br>";
                strHTML += "性别:" + objInfo.sex + "<br>";
                strHTML += "邮箱:" + objInfo.email + "<br>";
                strHTML += "时间:" + objInfo.date + "<hr>";
                //切换按钮显示的文字
                if ($(this).val() == strV0) {
                    $(this).val(strV1);
                } else {
                    $(this).val(strV0);
                }
                //显示处理后的数据
                $("#Tip").html(strHTML);
            });
        });
    </script>
</head>
<body>
   <div class="iframe">
         <div class="title">
              <input id="Button1" type="button"
                     class="btn" value="原始数据" />
         </div>
         <div class="content">
              <div id="Tip"></div>
         </div>
    </div>
</body>
</html>

 

3:上面的Json格式都是比较简单类型(只是name:value类型),还有一种是带嵌套平时我们也会经常碰到;Json中是以"[]"来包含;我们可以通过each进行循环显示出来;

<head>
    <title>jQuery 遍历JSON 数据</title>
    <script src="JScript/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var objData = {
            member: [{
                grade: "一年级",
                students: {
                    name: ["刘小芳", "李大明"]
                }
            }, {
                grade: "二年级",
                students: {
                    name: ["陈优", "王小海", "朱红"]
                }
            }, {
                grade: "三年级",
                students: {
                    name: ["张妍", "蔡霞"]
                }
               }]
           };
           function add_Grade() {
               var objmember = objData.member;
               var strHTML_0 = "";
               $.each(objmember, function(index) {
                   strHTML_0 += ‘<a href="javascript:" onclick="lnk_Click(‘ + index + ‘)">‘
                   + objmember[index].grade
                   + ‘</a>  ‘;
               });
               $(".title").html("年级优秀学生:" + strHTML_0);
           };
           function lnk_Click(i) {
               var objstudent = objData.member[i].students.name;
               var strHTML_1 = "";
               $.each(objstudent, function(index) {
                   strHTML_1 += ‘ ‘ + objstudent[index] + ‘ ‘;
               });
               $("#Tip").html(strHTML_1);
           };
           $(function() {
               add_Grade();
               lnk_Click(0)
           });
    </script>
</head>
<body>
   <div class="iframe">
         <div class="title"></div>
         <div class="content">
              <div id="Tip"></div>
         </div>
    </div>
</body>
</html>

 

4:在ASP.NET中操作JSON一般是与ashx进行结合;后台返回JSON在前台进行显示;下面的实例通过AJAX获得后台对象实体的字符串然后显示;

a:前台页面通过ajax调用后台的ashx程序获得数据

<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var strHtml = "";
            $("#BtnGetJson").click(function () {
                $.ajax({
                    url: "ToJson.ashx",
                    type: "GET",
                    dataType: "json",
                    success: function (data) {
                        $.each(data, function (index) {
                            strHtml += ‘ ‘ + data[index].Name + ‘ ‘ + data[index].PassWord + ‘<br/>‘;
                        });
                        $("#MyDiv").html(strHtml);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input id="BtnGetJson" type="button" value="获得JSON值" />
    <div id="MyDiv"
    </div>
    </form>
</body>
</html>

b:新建一个ToJson.ashx的一般处理程序类,让它将后台的实体对象进行转化返回到前台

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace JqueryForJson
{
    /// <summary>
    /// ToJson 的摘要说明
    /// </summary>
    public class ToJson : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            List<User> list = new List<User>();
            list.Add(new User() { Name = "踏浪帅", PassWord = "123456" });
            list.Add(new User() { Name = "wujy", PassWord = "456789" });
            string JsonStr = JsonHelper.GetJson<List<User>>(list);//如果是单个实体GetJson<User>(model)
            context.Response.Write(JsonStr);
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
 
    public class User
    {
        public string Name { get; set; }
 
        public string PassWord { get; set; }
    }
}

c:这边有一个把实体转化成JSON字符串的类,当然也可以通过其它方式进行转化;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;///记得引用这个命名空间
using System.IO;
using System.Text;
/// <summary>
/// Summary description for JsonHelper
/// </summary>
public class JsonHelper
{
    public JsonHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// <summary>
    /// 把对象序列化 JSON 字符串
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="obj">对象实体</param>
    /// <returns>JSON字符串</returns>
    public static string GetJson<T>(T obj)
    {
        //记住 添加引用 System.ServiceModel.Web
        /**
         * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦
         * */
        DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            json.WriteObject(ms, obj);
            string szJson = Encoding.UTF8.GetString(ms.ToArray());
            return szJson;
        }
    }
    /// <summary>
    /// 把JSON字符串还原为对象
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="szJson">JSON字符串</param>
    /// <returns>对象实体</returns>
    public static T ParseFormJson<T>(string szJson)
    {
        T obj = Activator.CreateInstance<T>();
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
        {
            DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
            return (T)dcj.ReadObject(ms);
        }
    }
}

  

感谢您的阅读,坚持每天进步一点点,离成功就更新一步;希望文章对您有所帮助;

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