$.toJSON的用法或把陣列轉換成json型別(轉)
1. html頁面全部程式碼
<html>
<head>
<title></title>
<script src="http://www.cnblogs.com/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/jquery.json-2.3.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;
}
}
}