Home  >  Article  >  Web Front-end  >  Introduction to how to use json for data transmission in the front and backend_javascript skills

Introduction to how to use json for data transmission in the front and backend_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:37:261055browse

In the previous blog, I wrote about using javascript to generate multiple groups of text , which can prevent data input from being displayed. Now we need to write these inputs into the database, and here we use json to pass them in.

First, let’s write about how the background generates the data to be transmitted
[html]

Copy code The code is as follows:

function generateDtb() {
//Write
var txtName = document.getElementById("txtName").value;
//Create array
var dtb = new Array();
//Write data to the array through loop and return
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() {
//Write
var txtName = document.getElementById("txtName").value;
//Create an array
var dtb = new Array();
//Write data into the array through a loop and return
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;
}

Convert the array into a json string and pass it to the background:
[html]
Copy code The code is as follows:

$(function () {
//Click botton1
$("#lbtnOK").click(function () {
var url = "DiscountManger.aspx?ajax=1";
var dtb = generateDtb();
// var strName = document.getElementById("txtName").value;
if (dtb == null)
{ }
else {
//Serialized object
var postdata = JSON.stringify (dtb);
//Asynchronous request
$.post(url, { json: postdata }, function (json) {
if (json) {
jBox.tip("Added successfully! ", "tip");
location.reload();
}
else {
jBox.tip("Add failed!", "tip");
location.reload( );
}
}, "json")
}
});
});
$(function () {
//Click botton1
$("#lbtnOK").click(function () {
var url = "DiscountManger.aspx?ajax=1";
var dtb = generateDtb();
// var strName = document. getElementById("txtName").value;
if (dtb == null)
{ }
else {
//Serialized object
var postdata = JSON.stringify(dtb);
//Asynchronous request
$.post(url, { json: postdata }, function (json) {
if (json) {
jBox.tip("Added successfully!", "Tip ");
location.reload();
}
else {
jBox.tip("Add failed!", "Tip");
location.reload();
}
}, "json")
}
});
});

Operations in the background:
First determine whether data needs to be transmitted
[html]
Copy code The code is as follows:

if (!IsPostBack)
{
//Determine whether to request asynchronously
if (Request.QueryString["ajax"] == "1")
{
ProcessRequest();
}
if (!IsPostBack)
{
//Determine whether to request asynchronously
if (Request.QueryString["ajax"] == "1")
{
ProcessRequest();
}

Process the data here:
[html]
Copy code The code is as follows:

///
/// Processing asynchronous requests
///

private void ProcessRequest()
{
// Deposit the strategy to be filled in
ArrayList arrDiscount = new ArrayList();
Response.ContentType = "text/html";
string json = Request.Form["json"];
// Deserialize 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();
//Discount plan name
enStrategyDiscount.name = newdtb.Rows[i]["Name"].ToString();
//Shop 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());
/ /Write data to the array
arrDiscount.Add(enStrategyDiscount);
}
//Write data to the database
IStrategyBLL strategy = new StrategyBLL();
if (strategy.AddStrategyDiscount( arrDiscount))
{
Response.Write("true");
Response.End();
}
else
{
Response.Write("false" );
Response.End();
}
}
///
/// Handling asynchronous requests
///

private void ProcessRequest()
{
//Save the policy to be filled in
ArrayList arrDiscount = new ArrayList();
Response.ContentType = "text/html";
string json = Request.Form["json"];
//Deserialize 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( );
//Discount plan name
enStrategyDiscount.name = newdtb.Rows[i]["Name"].ToString();
//Store 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());
//Write data to the array
arrDiscount.Add(enStrategyDiscount);
}
//Write data to the database
IStrategyBLL strategy = new StrategyBLL();
if (strategy.AddStrategyDiscount(arrDiscount))
{
Response.Write("true");
Response.End();
}
else
{
Response.Write("false");
Response.End();
}
}

Here, we need to put json Convert to datatable
[html]
Copy code The code is as follows:

///
/// Json to DataTable
///

///
// /
private DataTable Json2Dtb(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = jss.Deserialize(json) ;
DataTable dtb = new DataTable();
if (dic.Count > 0)
{
foreach (Dictionary 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;
}
///
// / Json to DataTable
///

///
/// private DataTable Json2Dtb(string json)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = jss.Deserialize(json);
DataTable dtb = new DataTable ();
if (dic.Count > 0)
{
foreach (Dictionary 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;
}

In this way, the data can be written to the database without refreshing.
Of course, if we have a datatable read from the database, what if it is displayed in the foreground through json.
First, we need to convert the datatable into json data
[html]
Copy code The code is as follows:

///
/// DataTable转Json
///

///
///
private string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary drow = new Dictionary();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}
///
/// DataTable转Json
///

///
///
private string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary drow = new Dictionary();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss.Serialize(dic);
}

然后写回到前台
[html]
复制代码 代码如下:

///
/// 处理异步请求
///

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();
}
///
/// 处理异步请求
///

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 = $("
");
for (var i = 0; i < json.length; i ) {
o1 = json[i];
var row = $("");
for (key in o1) {
var 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 = $("
");
for (var i = 0; i < json.length; i ) {
o1 = json[i];
var row = $("");
for (key in o1) {
var td = $("");
td.text(o1[key].toString());
td.appendTo(row);
}
row.appendTo(table);
}
table.appendTo($("#back"));
}

这样,就完成了json向后台传输数据和显示后台数据了,当然,这种传输方式只是传输的一种,如果是简单的字符串也可以用get和post进行传输,但是,javascript本身具有不安全性和不稳定行,对于一些比较重要的数据,建议还是寻找一些更可靠的方法。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn