1,遍历JSON
2,JSON.parse()和eval()
3,JSON.stringify()
页面:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><title></title>/* 引入Jquery库文件*/〈script type="text/javascript" src="/Script/jquery-1.10.2.min.js"></script><script type="text/javascript">$(function(){//创建JSON对象$("#EachJson").click(function(){var jsonObject = [{"id":1,"Name":"Rotu"},{"id":2,"Name":"Jack"}];//遍历JSON对象 index是索引,obj是迭代出来的对象$.each(json,function(index,obj){alert(index+"-----"+obj.id+"------"+obj.Name);});//将JSON对象转换成为JSON字符串var jsonString = JSON.stringify(json);//把JSON字符串转换成为JSON对象var jsonObject1 = JSON.parse(jsonString);//把JSON字符串转换成为JSON对象var jsonObject2 = eval("("+jsonObject1+")");});})</script></head><body><button id="EachJson">解析JSON</button></body></html>备注:遍历JSON数据的时候可以使用for语句和each语句,将JSON字符串转换成为JSON对象使用:JSON.parse()和eval()两个方法将JSON对象转换成为JSON对象使用:JSON.stringify()
通过Ajax请求服务端获取JSON数据,解析JSON
页面:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><title></title>/* 引入Jquery库文件*/〈script type="text/javascript" src="/Script/jquery-1.10.2.min.js"></script><script type="text/javascript">$(function(){//创建JSON对象$("#EachJson").click(function(){$.ajax({url:"/ashx/Reposne.ashx",type:"GET",dataType:"JSON",success:function(data){$.each(data,function(index,obj){alert(obj.StudentId+"---"+obj.StudentName);})}});});})</script></head><body><button id="EachJson">解析JSON</button></body></html>
服务端:(一般处理程序)
public class DealWithRequest:IHttpHandler{public void ProcessRequest(HttpContext context){context.Response.ContentType="text/plain";context.Response.Write(new JavaScriptSerializer().Serialize(new List<Student>(){new Student(){StudentId="001",StudentName="Rotu"},new Student(){StudentId="002",StudentName="Andy"},}));}}///构建实体public class Student{public string StudentNo{get;set;}public string StudentName{get;set;}}
