Using the Ajax method of jquery to read the table into Json_jquery

Source: Internet
Author: User
Tags datetime httpcontext serialization
1. Create the Users table
Copy Code code as follows:

CREATE TABLE Users
(
UserId int Identity (1,1) primary key,
UserName varchar (20)
)

INSERT into Users values (' Bradley ')
INSERT into Users values (' Dan ')

Copy Code code as follows:

CREATE TABLE Users
(
UserId int Identity (1,1) primary key,
UserName varchar (20)
)

INSERT into Users values (' Bradley ')
INSERT into Users values (' Dan ')

2. Create Jsonhelper class
Copy Code code as follows:

public class Jsonhelper
{
#region Serialization and deserialization
Serialization of
public static string jsonserializer<t> (t)
{
Serializes a T object into a memory stream using DataContractJsonSerializer.
DataContractJsonSerializer Jsonserializer = new DataContractJsonSerializer (typeof (T));
MemoryStream ms = new MemoryStream ();
Use the WriteObject method to write JSON data to the stream.
Jsonserializer.writeobject (MS, T);
Flow string
String jsonstring = Encoding.UTF8.GetString (ms. ToArray ());
Ms. Close ();
Replace the date string for JSON
String p = @ "\\/date\ ((\d+) \+\d+\) \\/";
MatchEvaluator matchevaluator = new MatchEvaluator (convertjsondatetodatestring);
Regex reg = new regex (p);
jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
return jsonstring;
}
public static T jsondeserialize<t> (String jsonstring)
{
Convert a string in the format "Yyyy-mm-dd HH:mm:ss" to "\/date (1294499956278+0800) \/" format
String p = @ "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchevaluator = new MatchEvaluator (convertdatestringtojsondate);
Regex reg = new regex (p);
jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
DataContractJsonSerializer jsonserializer=new DataContractJsonSerializer (typeof (T));
String flow
MemoryStream ms=new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));
Deserialize JSON-encoded data into T by using the DataContractJsonSerializer ReadObject method
T obj = (t) jsonserializer.readobject (MS);
return obj;
}
public static string convertjsondatetodatestring (match match)
{
string result = String. Empty;
DateTime datetime=new datetime (1970,1,1);
DateTime = Datetime.addmilliseconds (long. Parse (match. GROUPS[1]. Value));
DateTime = Datetime.tolocaltime ();
result = DateTime.ToString ("Yyyy-mm-dd HH:mm:ss");
return result;
}
private static string Convertdatestringtojsondate (Match m)
{
string result = String. Empty;
DateTime dt = DateTime.Parse (M.groups[0]. Value);
DT = dt. ToUniversalTime ();
TimeSpan ts = dt-datetime.parse ("1970-01-01");
result = String. Format ("\\/date ({0}+0800) \\/", TS. TotalMilliseconds);
return result;
}
#endregion

Object converted to JSON
public static string Objecttojson (Object obj)
{
JavaScriptSerializer js=new JavaScriptSerializer ();
Try
{
Return JS. Serialize (obj);
}
catch (Exception Exception)
{

throw new Exception (Exception. message);
}
}
converting data tables to collections
public static list<dictionary<string,object>> datatabletolist (DataTable DT)
{
List<dictionary<string,object>> list=new list<dictionary<string, object>> ();
foreach (DataRow DataRow in dt. Rows)
{
Dictionary<string,object> dic=new dictionary<string, object> ();
foreach (DataColumn dc in dt. Columns)
{
Dic. ADD (DC. COLUMNNAME,DATAROW[DC. ColumnName]);
}
List. ADD (DIC);
}
return list;
}
Table Convert to JSON
public static string Datatabletojson (DataTable dt)
{
Return Objecttojson (datatabletolist (DT));
}
}

Copy Code code as follows:

public class Jsonhelper
{
#region Serialization and deserialization
Serialization of
public static string jsonserializer<t> (t)
{
Serializes a T object into a memory stream using DataContractJsonSerializer.
DataContractJsonSerializer Jsonserializer = new DataContractJsonSerializer (typeof (T));
MemoryStream ms = new MemoryStream ();
Use the WriteObject method to write JSON data to the stream.
Jsonserializer.writeobject (MS, T);
Flow string
String jsonstring = Encoding.UTF8.GetString (ms. ToArray ());
Ms. Close ();
Replace the date string for JSON
String p = @ "\\/date\ ((\d+) \+\d+\) \\/";
MatchEvaluator matchevaluator = new MatchEvaluator (convertjsondatetodatestring);
Regex reg = new regex (p);
jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
return jsonstring;
}
public static T jsondeserialize<t> (String jsonstring)
{
Convert a string in the format "Yyyy-mm-dd HH:mm:ss" to "\/date (1294499956278+0800) \/" format
String p = @ "\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchevaluator = new MatchEvaluator (convertdatestringtojsondate);
Regex reg = new regex (p);
jsonstring = Reg. Replace (jsonstring, MatchEvaluator);
DataContractJsonSerializer jsonserializer=new DataContractJsonSerializer (typeof (T));
String flow
MemoryStream ms=new MemoryStream (Encoding.UTF8.GetBytes (jsonstring));
Deserialize JSON-encoded data into T by using the DataContractJsonSerializer ReadObject method
T obj = (t) jsonserializer.readobject (MS);
return obj;
}
public static string convertjsondatetodatestring (match match)
{
string result = String. Empty;
DateTime datetime=new datetime (1970,1,1);
DateTime = Datetime.addmilliseconds (long. Parse (match. GROUPS[1]. Value));
DateTime = Datetime.tolocaltime ();
result = DateTime.ToString ("Yyyy-mm-dd HH:mm:ss");
return result;
}
private static string Convertdatestringtojsondate (Match m)
{
string result = String. Empty;
DateTime dt = DateTime.Parse (M.groups[0]. Value);
DT = dt. ToUniversalTime ();
TimeSpan ts = dt-datetime.parse ("1970-01-01");
result = String. Format ("\\/date ({0}+0800) \\/", TS. TotalMilliseconds);
return result;
}
#endregion

Object converted to JSON
public static string Objecttojson (Object obj)
{
JavaScriptSerializer js=new JavaScriptSerializer ();
Try
{
Return JS. Serialize (obj);
}
catch (Exception Exception)
{

throw new Exception (Exception. message);
}
}
converting data tables to collections
public static list<dictionary<string,object>> datatabletolist (DataTable DT)
{
List<dictionary<string,object>> list=new list<dictionary<string, object>> ();
foreach (DataRow DataRow in dt. Rows)
{
Dictionary<string,object> dic=new dictionary<string, object> ();
foreach (DataColumn dc in dt. Columns)
{
Dic. ADD (DC. COLUMNNAME,DATAROW[DC. ColumnName]);
}
List. ADD (DIC);
}
return list;
}
Table Convert to JSON
public static string Datatabletojson (DataTable dt)
{
Return Objecttojson (datatabletolist (DT));
}
}

3. Add ashx code file
Copy Code code as follows:

public class Getdata:ihttphandler
{

public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
if (context. request["Action"]== "display")
{
Context. Response.Write (Jsonhelper.datatabletojson (GetAllUsers ()));
}
}

Static SqlConnection conn = new SqlConnection ("server=.; database=test;uid=sa;pwd=123456 ");
public static DataTable GetAllUsers ()
{
String sql = "SELECT * from users";
SqlDataAdapter adapter = new SqlDataAdapter (SQL, conn);
DataTable dt = new DataTable ();
Adapter. Fill (DT);
return DT;
}
public bool IsReusable
{
Get
{
return false;
}
}
}

Copy Code code as follows:

public class Getdata:ihttphandler
{

public void ProcessRequest (HttpContext context)
{
Context. Response.ContentType = "Text/plain";
if (context. request["Action"]== "display")
{
Context. Response.Write (Jsonhelper.datatabletojson (GetAllUsers ()));
}
}

Static SqlConnection conn = new SqlConnection ("server=.; database=test;uid=sa;pwd=123456 ");
public static DataTable GetAllUsers ()
{
String sql = "SELECT * from users";
SqlDataAdapter adapter = new SqlDataAdapter (SQL, conn);
DataTable dt = new DataTable ();
Adapter. Fill (DT);
return DT;
}
public bool IsReusable
{
Get
{
return false;
}
}
}

4. Front-End Call
Copy Code code as follows:

<title></title>
<script src= "Js/jquery-1.6.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
$ (function () {
var options = {
Type: ' Post ',
URL: "/getdata.ashx",
DataType: "JSON",
Data: {action: "Display"},
Success:function (data) {
var html = "<table border= ' 2px ' style= ' text-align:center;border-style:solid;border-width:2px;border-color:# 00ff00; ' ><tr><td>UserId</td><td>UserName</td></tr> ";
$.each (data, function (i, result) {
HTML + + "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName" + "</td></tr&" gt; ";
})
HTML + "</table>";
$ ("#divData"). HTML (HTML);
}
};
$.ajax (options);
});
</script>
<body>
<form id= "Form1" runat= "Server" >
<div id= "Divdata" >

</div>
</form>
</body>

Copy Code code as follows:

<title></title>
<script src= "Js/jquery-1.6.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
$ (function () {
var options = {
Type: ' Post ',
URL: "/getdata.ashx",
DataType: "JSON",
Data: {action: "Display"},
Success:function (data) {
var html = "<table border= ' 2px ' style= ' text-align:center;border-style:solid;border-width:2px;border-color:# 00ff00; ' ><tr><td>UserId</td><td>UserName</td></tr> ";
$.each (data, function (i, result) {
HTML + + "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName" + "</td></tr&" gt; ";
})
HTML + "</table>";
$ ("#divData"). HTML (HTML);
}
};
$.ajax (options);
});
</script>
<body>
<form id= "Form1" runat= "Server" >
<div id= "Divdata" >

</div>
</form>
</body>

5. Effect drawing

6. Can also read data through the Getjson method
Copy Code code as follows:


$.getjson ("/getdata.ashx", {action: "Display"},function (data) {
var html = "<table border= ' 2px ' style= ' text-align:center;border-style:solid;border-width:2px;border-color:# 00ff00; ' ><tr><td>UserId</td><td>UserName</td></tr> ";
$.each (data, function (i, result) {
HTML + + "<tr><td>" + result["UserId"] + "</td><td>" + result["UserName" + "</td></tr&" gt; ";
})
HTML + "</table>";
$ ("#divData"). HTML (HTML);
})

Copy Code code as follows:

$.getjson ("/getdata.ashx", {action: "Display"},function (data) {
var ht ml = "<table border= ' 2px ' style= ' text-align:center;border-style:solid;border-width:2px;border-color: #00ff00; ' ><tr><td>UserId</td><td>UserName</td></tr> ";
$.each (data, function (i, result) {
HTML = + <tr><td> + result["UserId"] + "</td><td>" + result["UserName"] + "</td></tr>";
})
HTML + </table>;
$ ("#divData"). HTML (HTML);
})
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.