JSON.stringify实例应用—将对象转换成JSON类型进行AJAX异步传值
在上一篇中,对JSON.stringify()方法有了初步的认识,并且做了一些简单的例子。本篇将进一步将JSON.stringify用在复杂些的实例中,例如如下需求:
在进jQuery AJAX异步传值时,用JSON.stringify()函数将数组转换成json类型(JSON:JavaScript Object Notation 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式),再传到一般处理程序中,在一般处理程序中,把得到的值进行反序列化Deserialize<T>(value)操作。
1.html代码:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <script src="js/jquery-1.8.2.min.js"></script> <script type="text/javascript"> $(function () { $("#btn").click(function () { var myArray = new Array(); var data = {}; data.name = "Tom"; data.age = 25; data.tel = "123456"; var data1 = {}; data1.name = "Tang"; data1.age = 27; data1.tel = "987654"; myArray.push(data); myArray.push(data1); //alert(JSON.stringify(array)); var params = {}; params.action = "OperationArray"; params.array = JSON.stringify(myArray); $.ajax({ url: "JSONstringify.ashx", data: params, type: "POST", dataType: "json", success: function (msg) { if (msg.OperateResult == "success") { if (msg.ResponseData.length > 0) { } } }, error: function (e) { alert("请求处理出错"); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <input type="button" id="btn" value="确定" /> </form> </body> </html>
2.一般处理程序代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; namespace JSONstringfy { /// <summary> /// JSONstringify 的摘要说明 /// </summary> public class JSONstringify : IHttpHandler { private JavaScriptSerializer json = new JavaScriptSerializer(); private string operateSuccess = "success"; private string operateFailed = "false"; public void ProcessRequest(HttpContext context) { string jsonObject = string.Empty; string action = context.Request["action"]; context.Response.ContentType = "application/json;charset=utf-8"; if (action == "OperationArray") jsonObject = OperationArray(context); context.Response.Write(jsonObject); } private string OperationArray(HttpContext context) { try { var array = context.Request["array"]; var arrayList = json.Deserialize<List<JSON_user>>(array);//反序列化,得到集合 foreach (var list in arrayList) { //这里可以获得数据,可以和数据库进行交互,传到前台, //本例子这里省略 } return json.Serialize(new { OperateResult = operateSuccess }); } catch (Exception e) { return json.Serialize(new { OperateResult = operateFailed, ResponseData = e.Message }); } } public bool IsReusable { get { return false; } } } }
3.JSON_user类:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace JSONstringfy { public class JSON_user { public string Name { get; set; } public string Age { get; set; } public string Tel { get; set; } } }
4.调试结果:
以上两图可以看到两条数据