后台把一个对象序列化发送到前台。注:不要序列化table,会有异常。应该是list或者字典
PhotoBLL bll = new PhotoBLL();
List<Photos> list = bll.GetAllPhotos();
//输出json格式的字符串
JavaScriptSerializer jss = new JavaScriptSerializer(); //JavaScriptSerializer命名空间 using System.Web.Script.Serialization;
string json = jss.Serialize(list);
context.Response.Write(json);
前端接收
方法一:当前端是用$.getJson方式:
$.getJSON("xxx.ashx, function (json) {
for (var i = 0; i < json.length; i++) {
var id = json[i].id;
...........
})
})
方法二:当前端是用$.post/get方式:
$.post("xxx.ashx?, function (data) {
var json = eval(data); //用eval解析json对象
for (var i = 0; i < json.length; i++) {
var id = json[i].id;
...........
})
})
前端用js拼json发送到后台,并反序列化获取数据
比如前端格式:
var data = { "photo": "{"PTitle":"" + title + "","PUrl":"" + url + "","PTypeId":1,"PUserId":1,"PDes":""}","type":1 };//斜杠是转义。别写错
$.ajax({
url: '/ashx/Enqeiry/ItemCode.ashx',
data: { "Enquiry": jsonTemp }, //serialize data
async: false,
type: 'post',
success: function (msg) {
if (msg == "ok") {
try {
opener.location.reload(); //刷新父页面
} catch (e) {
}
}
},
error: function () { }
});
后台接收并反序列化
string type = context.Request.Form["type"];
// {"PTitle":"","PUrl":"","PTypeId":1,"PUserId":1,"PDes":""}
string json = context.Request.Form["photo"];
JavaScriptSerializer jss = new JavaScriptSerializer();
//把json格式的字符串 转化成photos对象
Photos photo = jss.Deserialize<Photos>(json);