Posted in Javascript onApril 11, 2013
上一篇博客写到用javascript生成多组文本,可以让数据的输入不受显示,现在我们需要把这些输入写入数据库,这里就用到json传入。
首先,我们来写一下后台如何生成要传输的数据
[html]
function generateDtb() { //写入 var txtName = document.getElementById("txtName").value; //创建数组 var dtb = new Array(); //通过循环把数据写入到数组并返回 for (var i = 0; i < firstGroup.length; i++) { var row = new Object(); row.Name = txtName; row.fullMoney = firstGroup[i].value; row.discount = secondGroup[i].value; dtb.push(row); } return dtb; } function generateDtb() { //写入 var txtName = document.getElementById("txtName").value; //创建数组 var dtb = new Array(); //通过循环把数据写入到数组并返回 for (var i = 0; i < firstGroup.length; i++) { var row = new Object(); row.Name = txtName; row.fullMoney = firstGroup[i].value; row.discount = secondGroup[i].value; dtb.push(row); } return dtb; }
把数组转换成json串传入到后台:
[html]
$(function () { //点击botton1 $("#lbtnOK").click(function () { var url = "DiscountManger.aspx?ajax=1"; var dtb = generateDtb(); // var strName = document.getElementById("txtName").value; if (dtb == null) { } else { //序列化对象 var postdata = JSON.stringify(dtb); //异步请求 $.post(url, { json: postdata }, function (json) { if (json) { jBox.tip("添加成功!", "提示"); location.reload(); } else { jBox.tip("添加失败!", "提示"); location.reload(); } }, "json") } }); }); $(function () { //点击botton1 $("#lbtnOK").click(function () { var url = "DiscountManger.aspx?ajax=1"; var dtb = generateDtb(); // var strName = document.getElementById("txtName").value; if (dtb == null) { } else { //序列化对象 var postdata = JSON.stringify(dtb); //异步请求 $.post(url, { json: postdata }, function (json) { if (json) { jBox.tip("添加成功!", "提示"); location.reload(); } else { jBox.tip("添加失败!", "提示"); location.reload(); } }, "json") } }); });
在后台的操作:
首先判断是否需要传输数据
[html]
if (!IsPostBack) { //判断是否异步请求 if (Request.QueryString["ajax"] == "1") { ProcessRequest(); } if (!IsPostBack) { //判断是否异步请求 if (Request.QueryString["ajax"] == "1") { ProcessRequest(); }
在这里进行对数据的处理:
[html]
/// <summary> /// 处理异步请求 /// </summary> private void ProcessRequest() { //存入要填写的策略 ArrayList arrDiscount = new ArrayList(); Response.ContentType = "text/html"; string json = Request.Form["json"]; //反序列化DataTable if (json == null) { return; } else { DataTable newdtb = Json2Dtb(json); for (int i = 0; i < newdtb.Rows.Count; i++) { Entity.StrategyDiscount enStrategyDiscount = new Entity.StrategyDiscount(); //打折方案名 enStrategyDiscount.name = newdtb.Rows[i]["Name"].ToString(); //商店ID enStrategyDiscount.shopId = long.Parse(LoginInfo.ShopID); enStrategyDiscount.fullMoney = Convert.ToDecimal(newdtb.Rows[i]["fullMoney"].ToString()); enStrategyDiscount.discount = Convert.ToDecimal(newdtb.Rows[i]["discount"].ToString()); //写入数据到数组 arrDiscount.Add(enStrategyDiscount); } //写入数据到数据库 IStrategyBLL strategy = new StrategyBLL(); if (strategy.AddStrategyDiscount(arrDiscount)) { Response.Write("true"); Response.End(); } else { Response.Write("false"); Response.End(); } } /// <summary> /// 处理异步请求 /// </summary> private void ProcessRequest() { //存入要填写的策略 ArrayList arrDiscount = new ArrayList(); Response.ContentType = "text/html"; string json = Request.Form["json"]; //反序列化DataTable if (json == null) { return; } else { DataTable newdtb = Json2Dtb(json); for (int i = 0; i < newdtb.Rows.Count; i++) { Entity.StrategyDiscount enStrategyDiscount = new Entity.StrategyDiscount(); //打折方案名 enStrategyDiscount.name = newdtb.Rows[i]["Name"].ToString(); //商店ID enStrategyDiscount.shopId = long.Parse(LoginInfo.ShopID); enStrategyDiscount.fullMoney = Convert.ToDecimal(newdtb.Rows[i]["fullMoney"].ToString()); enStrategyDiscount.discount = Convert.ToDecimal(newdtb.Rows[i]["discount"].ToString()); //写入数据到数组 arrDiscount.Add(enStrategyDiscount); } //写入数据到数据库 IStrategyBLL strategy = new StrategyBLL(); if (strategy.AddStrategyDiscount(arrDiscount)) { Response.Write("true"); Response.End(); } else { Response.Write("false"); Response.End(); } }
这里,我们需要把json转换成datatable
[html]
/// <summary> /// Json转DataTable /// </summary> /// <param name="json"></param> /// <returns></returns> private DataTable Json2Dtb(string json) { JavaScriptSerializer jss = new JavaScriptSerializer(); ArrayList dic = jss.Deserialize<ArrayList>(json); DataTable dtb = new DataTable(); if (dic.Count > 0) { foreach (Dictionary<string, object> drow in dic) { if (dtb.Columns.Count == 0) { foreach (string key in drow.Keys) { dtb.Columns.Add(key, drow[key].GetType()); } } DataRow row = dtb.NewRow(); foreach (string key in drow.Keys) { row[key] = drow[key]; } dtb.Rows.Add(row); } } return dtb; } /// <summary> /// Json转DataTable /// </summary> /// <param name="json"></param> /// <returns></returns> private DataTable Json2Dtb(string json) { JavaScriptSerializer jss = new JavaScriptSerializer(); ArrayList dic = jss.Deserialize<ArrayList>(json); DataTable dtb = new DataTable(); if (dic.Count > 0) { foreach (Dictionary<string, object> drow in dic) { if (dtb.Columns.Count == 0) { foreach (string key in drow.Keys) { dtb.Columns.Add(key, drow[key].GetType()); } } DataRow row = dtb.NewRow(); foreach (string key in drow.Keys) { row[key] = drow[key]; } dtb.Rows.Add(row); } } return dtb; }
这样,就可以把数据无刷新的写入到数据库。
当然,如果我们有一个从数据库读取的datatable,如果通过json显示在前台呢。
首先,我们需要把datatable转换为json数据
[html]
/// <summary> /// DataTable转Json /// </summary> /// <param name="dtb"></param> /// <returns></returns> private string Dtb2Json(DataTable dtb) { JavaScriptSerializer jss = new JavaScriptSerializer(); ArrayList dic = new ArrayList(); foreach (DataRow row in dtb.Rows) { Dictionary<string, object> drow = new Dictionary<string, object>(); foreach (DataColumn col in dtb.Columns) { drow.Add(col.ColumnName, row[col.ColumnName]); } dic.Add(drow); } return jss.Serialize(dic); } /// <summary> /// DataTable转Json /// </summary> /// <param name="dtb"></param> /// <returns></returns> private string Dtb2Json(DataTable dtb) { JavaScriptSerializer jss = new JavaScriptSerializer(); ArrayList dic = new ArrayList(); foreach (DataRow row in dtb.Rows) { Dictionary<string, object> drow = new Dictionary<string, object>(); foreach (DataColumn col in dtb.Columns) { drow.Add(col.ColumnName, row[col.ColumnName]); } dic.Add(drow); } return jss.Serialize(dic); }
然后写回到前台
[html]
/// <summary> /// 处理异步请求 /// </summary> private void ProcessRequest() { Response.ContentType = "text/html"; string json = Request.Form["json"]; //反序列化DataTable DataTable newdtb = Json2Dtb(json); //序列化DataTable为JSON string back = Dtb2Json(newdtb); Response.Write(back); Response.End(); } /// <summary> /// 处理异步请求 /// </summary> private void ProcessRequest() { Response.ContentType = "text/html"; string json = Request.Form["json"]; //反序列化DataTable DataTable newdtb = Json2Dtb(json); //序列化DataTable为JSON string back = Dtb2Json(newdtb); Response.Write(back); Response.End(); }
在前台接受显示:
[html]
$(function() { //点击botton1 $("#botton1").click(function() { createTable(json); }); }); //显示Json中的数据 function createTable(json) { var table = $("<table border='1'></table>"); for (var i = 0; i < json.length; i++) { o1 = json[i]; var row = $("<tr></tr>"); for (key in o1) { var td = $("<td></td>"); td.text(o1[key].toString()); td.appendTo(row); } row.appendTo(table); } table.appendTo($("#back")); } $(function() { //点击botton1 $("#botton1").click(function() { createTable(json); }); }); //显示Json中的数据 function createTable(json) { var table = $("<table border='1'></table>"); for (var i = 0; i < json.length; i++) { o1 = json[i]; var row = $("<tr></tr>"); for (key in o1) { var td = $("<td></td>"); td.text(o1[key].toString()); td.appendTo(row); } row.appendTo(table); } table.appendTo($("#back")); }
这样,就完成了json向后台传输数据和显示后台数据了,当然,这种传输方式只是传输的一种,如果是简单的字符串也可以用get和post进行传输,但是,javascript本身具有不安全性和不稳定行,对于一些比较重要的数据,建议还是寻找一些更可靠的方法。
如何使用json在前后台进行数据传输实例介绍
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@