DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JSON基礎 >> json 入門學習筆記 示例代碼
json 入門學習筆記 示例代碼
編輯:JSON基礎     

Json介紹:

  JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。易於人閱讀和編寫。
      json 官方網站 http://www.json.org/
      json.net 下載地址 http://json.codeplex.com/releases/view/37810

Demo:

  

描述:
  點擊獲取按鈕後,將請求頁面,獲取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。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved