json 入门学习笔记 示例代码

Json介绍:

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。
      json 官方网站 http://www.json.org/
      json.net 下载地址 http://json.codeplex.com/releases/view/37810

Demo:

json 入门学习笔记 示例代码

描述:
  点击获取按钮后,将请求页面,获取json数据,填充到表格
html代码:

代码如下:

<!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 runat="server"> 
<title></title> 
<script type="text/jscript" src="../jquery/jquery-1.4.2.min.js"></script> 
<script language="javascript" type="text/javascript"> 
$(function() { 
$("#Button1").click(function() { 
$.get("json1.aspx?m=m", null, function(callbackmsg) { 
var product = eval(callbackmsg); 
ShowProduct(product) 
}) 
}); 
}) 
function ShowProduct(callbackmsg) { 
var row=''; 
for (var u in callbackmsg) { 
var len = callbackmsg[u].length; 
row += '<tr>'; 
row += '<td>' + callbackmsg[u].Name + '</td>'; 
row += '<td>' + callbackmsg[u].Price + '</a></td>'; 
row += '<td>' + callbackmsg[u].Size + '</td>'; 
row += '</tr>'; 
} 
$("#body").html(row); 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<input id="Button1" type="button" value="获取" /> 
</div> 
<table> 
<thead> 
<tr> 
<th> 
名称 
</th> 
<th> 
价格 
</th> 
<th> 
大小 
</th> 
</tr> 
</thead> 
<tbody id="body"> 
</tbody> 
</table> 
</form> 
</body> 
</html>

后台代码:

代码如下:

public partial class json1 : System.Web.UI.Page 
{ 
protected void Page_Load(object sender, EventArgs e) 
{ 
if (HttpContext.Current.Request.QueryString["m"] != null) 
{ 
List<Product> Products = new List<Product>(); 
Products.Add(new Product() { Name = "笔记本", Price = "4.2", Size = "30x50" }); 
Products.Add(new Product() { Name = "尺子", Price = "1.2", Size = "30x50" }); 
Products.Add(new Product() { Name = "书", Price = "36", Size = "30x50" }); 
Products.Add(new Product() { Name = "钢笔", Price = "6.0", Size = "30x50" }); 
Products.Add(new Product() { Name = "铅笔", Price = "2.2", Size = "30x50" }); 
string json = JsonConvert.SerializeObject(Products); 
Response.Write(json); 
Response.End(); 
} 
} 
} 
public class Product 
{ 
public string Name { get; set; } 
public string Size { get; set; } 
public string Price { get; set; } 
}

知识点:
  1.json官方提供了用于.net操作的dll类库,JsonConvert.SerializeObject将.net对象序列化为json。
  2.Javascript读取json对象var product = eval(callbackmsg)。
  3.Javascript读取json值callbackmsg[u].Name。

相关推荐