Details about asynchronous processing of Json data using Jquery Ajax.

Source: Internet
Author: User
Tags net serialization javascript array

The so-called Ajax. Here we will talk about two methods.
Method 1: (Microsoft has its own Ajax Framework)
In Asp.net, Microsoft has its own Ajax framework. This is to introduce the using System. Web. Services space in the page background. cs file and then define the static method (add [WebMethod] before the method).
[WebMethod]
Public static string ABC (string ABC)
{
Return ABC;
}
Now let's talk about how front-end Js processes the data returned by the backend. Jquery can be used to process the returned pure html, json, Xml, and other data. here we will demonstrate that the returned data includes string, set (List <>), and class.
But they all return the Json format (Json is lightweight and easier to process than XML). Let's see how the front-end parses the data.
The Code is as follows:
Front-end page: Copy codeThe Code is as follows: <% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default2.aspx. cs" Inherits = "Default2" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN"
Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
<Style type = "text/css">
. Hover
{
Cursor: pointer;/* Small hand */
Background: # ffc;/* background */
}
</Style>
<Script type = "text/javascript" src = "js/jquery-1.3.2-vsdoc2.js"> </script>
<Script type = "text/javascript">
// Call without Parameters
$ (Document). ready (function (){
$ ('# Btn1'). click (function (){
$. Ajax ({
Type: "POST", // WebService access request using Post
ContentType: "application/json ",
Url: "Default2.aspx/HelloWorld", // address and method name combination of WebService call ---- WsURL/method name
Data: "{}", // here is the parameter to be passed, in the format of data: "{paraName: paraValue}", as shown below
DataType: 'json', // WebService returns the json type
Success: function (result) {// callback function, result, Return Value
Alert (result. d );
}
});
});
});
// Call with Parameters
$ (Document). ready (function (){
$ ("# Btn2"). click (function (){
$. Ajax ({
Type: "POST ",
ContentType: "application/json ",
Url: "Default2.aspx/GetWish ",
Data: "{value1: 'wishful thinking ', value2: 'Good luck', value3: 'niu Niu ', value4: 2009 }",
DataType: 'json ',
Success: function (result ){
Alert (result. d );
}
});
});
});
// Return the Set (referenced from the network, which is very helpful)
$ (Document). ready (function (){
$ ("# Btn3"). click (function (){
$. Ajax ({
Type: "POST ",
ContentType: "application/json ",
Url: "Default2.aspx/GetArray ",
Data: "{I: 10 }",
DataType: 'json ',
Success: function (result ){
$ (Result. d). each (function (){
Alert (this );
$ ('# Dictionary'). append (this. toString () + "");
// Alert (result. d. join ("| "));
});
}
});
});
});
// Return the composite type
$ (Document). ready (function (){
$ ('# Btn4'). click (function (){
$. Ajax ({
Type: "POST ",
ContentType: "application/json ",
Url: "Default2.aspx/GetClass ",
Data :"{}",
DataType: 'json ',
Success: function (result ){
$ (Result. d). each (function (){
// Alert (this );
$ ('# Dictionary'). append (this ['id'] + "" + this ['value']);
// Alert (result. d. join ("| "));
});
}
});
});
});
// Ajax provides feedback to users. They can add two methods to jQuery objects for callback before and after Ajax.
// However, Ajax monitoring is global.
$ (Document). ready (function (){
$ ('# Loading'). ajaxStart (function (){
$ (This). show ();
}). AjaxStop (function (){
$ (This). hide ();
});
});
// Move the cursor to the removal effect. You can use commas (,) to separate multiple elements.
$ (Document). ready (function (){
$ ('Btn '). hover (function (){
$ (This). addClass ('hover ');
}, Function (){
$ (This). removeClass ('hover ');
});
});
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Input type = "button" id = "btn1" value = "HelloWorld"/>
<Input type = "button" id = "btn2" value = "input parameter"/>
<Input type = "button" id = "btn3" value = "return set"/>
<Input type = "button" id = "btn4" value = "Return compound type"/>
</Div>
<Div id = "dictionary"> dictionary
</Div>
</Form>
</Body>
</Html>

Background. cs FileCopy codeThe Code is as follows: using System;
Using System. Collections;
Using System. Collections. Generic;
Using System. Configuration;
Using System. Data;
Using System. Linq;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. HtmlControls;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. Services;
Public partial class Default2: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
[WebMethod]
Public static string HelloWorld ()
{
Return "123 ---> 456 ";
}
[WebMethod]
Public static string ABC (string ABC)
{
Return ABC;
}
[WebMethod]
Public static string GetWish (string value1, string value2, string value3, int value4)
{
Return string. Format ("Wish you {0}, {1}, {2}", value1, value2, value3, value4 in {3} years );
}
/// <Summary>
/// Return the set
/// </Summary>
/// <Param name = "I"> </param>
/// <Returns> </returns>
[WebMethod]
Public static List <int> GetArray (int I)
{
List <int> list = new List <int> ();
While (I> = 0)
{
List. Add (I --);
}
Return list;
}
/// <Summary>
/// Return a composite type
/// </Summary>
/// <Returns> </returns>
[WebMethod]
Public static Class1 GetClass ()
{
Return new Class1 {ID = "1", Value = ""};
}
Public class Class1
{
Public string ID {get; set ;}
Public string Value {get; set ;}
}
}

Jquery is used to return all types of returned data (string, set (List <>) and Class) in Json format. Why is result. d used?
Here we will introduce the Json
Json is a Javascript Object or array.
Json format 1: javascript Object {"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa "}
Json Format 2: javascript Array [{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa "},
{"FirstName": "Jason", "lastName": "Hunterwang", "email": "bbbb"}]
Of course, javascript arrays and objects can be nested. For example, in Form 1, "Brett" can be replaced with a Js array or Js object. Which form does Microsoft Ajax return? It is the first one.
By default, the Microsoft framework returns a {"d": "data returned in the background"} Here we use the test in the above example as follows:
If the string type is returned in the above example, Firefox debugging is as follows:

FireFox debugging is as follows:

The returned data is stored in the d attribute of the Js object. That's why we always use result. d to retrieve the data returned by the Microsoft framework.

Method 1 is not commonly used. method 2 is generally used much.
Method 2: (create a general handler named. ashx file)
In this way, we need to manually write the returned Json data in the ashx file and return it to the front-end.
You can configure ashx to Json format 1 or Json Format 2.
The Js Code of the Default. aspx page is as follows:

Copy codeThe Code is as follows: $. ajax ({
Type: "POST ",
Url: "Handler. ashx ",
DataType: "json ",
Success: function (data ){
Alert (data. name); // The returned result is in Json format 1 (Js object)
/* The returned result is in Json format (Js object)
$ (Data). each (function (I ){
Alert (data [I]. name );
});
*/
}
});

The Handler. ashx code is as follows:Copy codeThe Code is as follows: <% @ WebHandler Language = "C #" Class = "Handler" %>
Using System;
Using System. Web;
Using System. Collections;
Using System. Collections. Generic;
Using System. Web. Script. Serialization;
Public class Handler: IHttpHandler {
Public void ProcessRequest (HttpContext context ){
JavaScriptSerializer jss = new JavaScriptSerializer ();
Context. Response. ContentType = "text/plain ";
// Return a Js object in Json format
String data = "{\" name \ ": \" wang \ ", \" age \ ": 25 }";
// The returned result is a two-Js array in Json format.
// String data = "[{\" name \ ": \" wang \ ", \" age \ ": 25 },{ \" name \": \ "zhang \", \ "age \": 22}] ";
Context. Response. Write (data );
}
Public bool IsReusable {
Get {
Return false;
}
}
}

The above is basically the second method. Some people may not like to spell strings. What is the best way? The answer is yes. Microsoft has good support for Json.
Let's take the example and say we only need to change Handler. ashx.
The Handler. ashx code is as follows:Copy codeThe Code is as follows: <% @ WebHandler Language = "C #" Class = "Handler" %>
Using System;
Using System. Web;
Using System. Collections;
Using System. Collections. Generic; // Dictionary <,> required for the set of key-value pairs
Using System. Web. Script. Serialization; // required by the JavaScriptSerializer class
Public class Handler: IHttpHandler {
Public void ProcessRequest (HttpContext context ){
JavaScriptSerializer jss = new JavaScriptSerializer ();
Context. Response. ContentType = "text/plain ";
Dictionary <string, string> drow = new Dictionary <string, string> ();
Drow. Add ("name", "Wang ");
Drow. Add ("age", "24 ");
Context. Response. Write (jss. Serialize (drow ));
}
Public bool IsReusable {
Get {
Return false;
}
}
}

JavaScriptSerializer in ASP. Net provides us with a good method.

Jss. Serialize (drow) converts the drow's Dictionary <string, int> (set of keys and values) data type to Json data format.

The debugging result is as follows (the preceding example outputs a key-value multi-set, that is, a Js object in the Json format)

What if I want to output Json Format 2 (Js array? We only need to change part of it.

The Handler. ashx code is as follows:Copy codeThe Code is as follows: <% @ WebHandler Language = "C #" Class = "Handler" %>
Using System;
Using System. Web;
Using System. Collections;
Using System. Collections. Generic;
Using System. Web. Script. Serialization;
Public class Handler: IHttpHandler {
Public void ProcessRequest (HttpContext context ){
JavaScriptSerializer jss = new JavaScriptSerializer ();
Context. Response. ContentType = "text/plain ";
List <Dictionary <string, string >>_list = new list <Dictionary <string, string> ();
Dictionary <string, string> drow = new Dictionary <string, string> ();
Drow. Add ("name", "Wang ");
Drow. Add ("age", "24 ");
Dictionary <string, string> drow1 = new Dictionary <string, string> ();
Drow1.Add ("name", "Zhang ");
Drow1.Add ("age", "35 ");
_ List. Add (drow );
_ List. Add (drow1 );
Context. Response. Write (jss. Serialize (_ list ));
}
Public bool IsReusable {
Get {
Return false;
}
}
}

The debugging result is as follows (the preceding example outputs the Js array in Json Format 2)

The basic concepts are also mentioned here. Another common example here is how to convert the Abel to the Json format so that the front-end page can be called.

Write a method in Handler. ashx.Copy codeThe Code is as follows: // <summary>
/// Convert DataTable to 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 );
}

In fact, you can also convert the Json format to the Abel format. The method is as follows:Copy codeThe Code is as follows: // <summary>
/// Convert Json to 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;
}

The returned Json is displayed in a table.
The front-end page JS is as follows:Copy codeThe Code is as follows: $. ajax ({
Type: "POST ",
Url: "Handler. ashx ",
DataType: "json ",
Success: function (data ){
Var table = $ ("<table border = '1'> </table> ");
For (var I = 0; I <data. length; I ++ ){
O1 = data [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 "));
}
});

Let's talk about two more Js knowledge points in the previous example.
1. If the data in Json is returned as an array, data [I]. name can also be expressed as data [I] ["name"].
2. If you want to access all attributes of a Js object, traverse the Js object.Copy codeThe Code is as follows: success: function (data ){
$ (Data). each (function (I ){
For (key in this) // traverses all attributes of the Js object
Alert (data [I] [key]);
// Data [I]. key cannot be changed here. Otherwise, the key becomes an attribute rather than the preceding key variable.
});
}

The front-end Json data is also transferred to the back-end and parsed as a Abel.
Here, I will convert Abel into Json and Json into DataTabel as an example.
Source code download
If you are interested in asp.net serialization and deserialization

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.