DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 如何使用json在前後台進行數據傳輸實例介紹
如何使用json在前後台進行數據傳輸實例介紹
編輯:關於JavaScript     
上一篇博客寫到用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本身具有不安全性和不穩定行,對於一些比較重要的數據,建議還是尋找一些更可靠的方法。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved