using System.Runtime.Serialization.Json;
/// <summary>
/// json格式序列化
/// </summary>
public class JsonList : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
string action = Request.Form["action"];
string OrderNum = context.Request["ordernum"];
ArrayList tmp = new ArrayList();
tmp.Add("{\"gName\":\"张三1\",\"description\":\"描述1\"}");
tmp.Add("{\"gName\":\"张三2\",\"description\":\"描述2\"}");
tmp.Add("{\"gName\":\"张三3\",\"description\":\"描述3\"}");
tmp.Add("{\"gName\":\"张三4\",\"description\":\"描述4\"}");
tmp.Add("{\"gName\":\"张三5\",\"description\":\"描述5\"}");
tmp.Add("{\"gName\":\"张三6\",\"description\":\"描述6\"}");
tmp.Add("{\"gName\":\"张三7\",\"description\":\"描述7\"}");
tmp.Add("{\"gName\":\"张三8\",\"description\":\"描述8\"}");
tmp.Add("{\"gName\":\"张三9\",\"description\":\"描述9\"}");
tmp.Add("{\"gName\":\"张三10\",\"description\":\"描述10\"}");
if (action == "one")
{
JavaScriptSerializer js = new JavaScriptSerializer();
Employee emp = new Employee()
{
gName = "梦之队",
description = "描述"
};
string jsonResult = "[" + js.Serialize(emp) + "]";
context.Response.Write(jsonResult);
}
else if (action == "two")
{
Employee emp = new Employee();
emp.gName = "方式二";
emp.description = "描述";
string jsonResult = "[" + this.JsonSerializa<Employee>(emp) + "]";
context.Response.Write(jsonResult);
}
else if (action == "three")
{
/*用javaScriptSerializer来生成JSON数据*/
var employees = new List<Employee>();
employees.Add(new Employee
{
gName = "张三方式三",
description = "描述1"
});
employees.Add(new Employee
{
gName = "张三方式三",
description = "描述2"
});
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
var jsonResult = javaScriptSerializer.Serialize(employees);
context.Response.Write(jsonResult);
}
else
{
string jsonResult = "[" + string.Join(",", (string[])tmp.ToArray(typeof(string))) + "]";
context.Response.Write(jsonResult);
}
}
/// <summary>
/// json序列号
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public string JsonSerializa<T>(T t)
{
DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
zer.WriteObject(ms, t);
string jsonstring = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonstring;
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class Employee
{
public string description { get; set; }
public string gName { get; set; }
}
方式一:
后台处理
[HttpPost] public JsonResult SendEmail() { int success = 0; int fail = 0; int count = Convert.ToInt32(Request.Form["countnum"]); for (int i = 0; i < count; i++) { if (i % 2 == 0) success += 1; else fail += 1; } JsonResult jsonResult = new JsonResult { Data = new { successCount = success, failCount = fail, } }; return Json(jsonResult); }前台输出
function OpenEmail1() { $.ajax({ url: "/tblGroups/SendEmail", type: 'post', data: { countnum: $("#hidCount").val() }, beforeSend: function () { $("#loading").show(); }, error: function () { alert("出错了"); }, success: function (data) { $("#lblSuccess").html(data.Data.successCount); $("#lblFail").html(data.Data.failCount); $("#loading").hide(); $("#emailDIV").show(); $("#fade").show(); } }); }方式二:
后台代码:
[HttpPost] public JsonResult GetModel(FormCollection collection) { string Action = collection["action"].ToString(); string strid = Request.Form["id"].ToString(); Guid id = new Guid(strid); return Json(GetGroupsModel(id)); } /// <summary> /// 返回一个实体 /// </summary> /// <param name="gid">id</param> /// <returns></returns> private IEnumerable<tblGroups> GetGroupsModel(Guid gid) { var query = from g in db.tblGroups where g.Id == gid select new { Id = g.Id, Name = g.Name, Description = g.Description, SumCount = (from m in db.tblMembers where m.GroupId == g.Id select m).Count() }; return query.ToList().Select(C => new tblGroups { Id = C.Id, Name = C.Name, Description = C.Description, CountNum = C.SumCount }); }前台代码:
function OpenWin(id) { $("#light").show(); $("#fade").show(); $.ajax({ url: "/tblGroups/GetModel", type: 'post', data: { action: "GetModel", id: id }, success: function (data) { for (var i = 0; i < data.length; i++) { $("#lblName").html(data[i].Name); $("#lblCount").html(data[i].CountNum); $("#hidCount").val(data[i].CountNum); } } }); }
结果集是object类型循环输出
function sel() { $.ajax({ url: "/Trace/select", type: "post", data: { name: $("#selBatch").val() }, success: function (data) { var objs = data; var str = ""; $("#tbd").html(""); for (var n in objs) { str += "<tr>"; str += "<td>" + objs[n].BatchID + "</td>"; str += "<td>" + objs[n].Path + "</td>"; str += "</tr>"; } $("#tbd").html(str); } }); }
Ajax请求
function InitData(pageindx, ofile, otype) { $.ajax({ url: '/Campaign/Ajax_Read', //请求地址 type: 'POST', //请求方法 dataType: 'json', //返回数据类型(json,xml,html) data: { //传递参数 action: 'paging', pagenum: pageindx, orderFile: ofile, orderType: otype }, beforeSend: function () { //发送请求前 $("#loading").show(); }, error: function () { //出现错误时提示状态 alert("出错了"); }, complete: function() { //请求完成后 alert("请求完成后提示信息") }, success: function(data) { //请求成功时返回数据 var objs = jQuery.parseJSON(data); for (var i = 0; i < objs.length; i++) { $("#lblSuccess").html(objs[i].successCount); $("#lblFail").html(objs[i].failCount); } } }) }
async设置异步同步并设置数组
function createRandomData() { $.ajax({ url: '/Handler/JsonList.ashx', type: 'POST', async: false, data: { action: '' }, success: function(responseText) { var re = responseText.toJson(); var data123 = []; $.each(re, function(i, n) { data123.push({ Id: i + 1, GroupName: n.gName, Description: n.description, Member: n.member, Email: n.email }); }); } }); }
方式三
后台代码
DataSet ds = DbHelperSQL.Query(sql.ToString()); ArrayList tmp = new ArrayList(); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { tmp.Add("{Times:" + ds.Tables[0].Rows[i]["Times"] + "," + "Totals:" + ds.Tables[0].Rows[i]["Totals"] + "," + "Drinking:" + ds.Tables[0].Rows[i]["Drinking"] + "," + "Surplus:" + ds.Tables[0].Rows[i]["Surplus"] + "}"); } string jsonResult = "[" + string.Join(",", (string[])tmp.ToArray(typeof(string))) + "]"; return jsonResult;
$.ajax({ async: false, url: "@Url.Action("GetModel", "BarChart")", type: 'post', data: { name: name, area: area, begin: begin, end: end }, success: function (data) { var objs = eval(data); for (var i = 0; i < objs.length; i++) { dataTime.push(objs[i].Times); dataDrinking.push(objs[i].Drinking); dataSurplus.push(objs[i].Surplus); } } });
后台object循环输出
ResultMessage<object> result = new ResultMessage<object>(); result = busi.GetListBatch(); string[] arr = result.Data as string[]; List<SelectListItem> select1 = new List<SelectListItem>(); select1.Add(new SelectListItem { Text = "请选择...", Value = "" }); for (int i = 0; i < arr.Length; i++) { select1.Add(new SelectListItem { Text = arr[i].ToString(), Value = arr[i].ToString() }); }