In detail Jquery Ajax asynchronously processes JSON data.

Source: Internet
Author: User
Tags httpcontext javascript array

What is called async, what is Ajax. I don't talk about XMLHttpRequest. Popular speaking async is the foreground page JavaScript can invoke the back-end method. This way, there is no refresh. The so-called Ajax. Here we talk about two ways

method One: ( Microsoft has its own AJAX framework)

In ASP. Microsoft has its own AJAX framework. A using System.Web.Services space is introduced into the page background. cs file and then a static method is defined (method preceded by [WebMethod])

[WebMethod]
public static string ABC (string ABC)
{
return ABC;
}

Okay, now let's talk about how the foreground JS handles the data returned in the background, using jquery to process the returned pure Html,json,xml data. Here we demonstrate that the returned data has a string, a collection (list<>), and a class.

But all return JSON format (JSON lightweight is easier to handle than XML). See how the front desk parses the data.

The code is as follows:

Front page:

<%@ 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" >
<title> Untitled Page </title>
<style type= "Text/css" >
. hover
{
Cursor:pointer; /* Small hands */
Background: #ffc; /* Background */
}
</style>
<script type= "Text/javascript" src= "Js/jquery-1.3.2-vsdoc2.js" ></script>
<script type= "Text/javascript" >
No parameter calls
$ (document). Ready (function () {
$ (' #btn1 '). Click (function () {
$.ajax ({
Type: "POST",//Access WebService use post to request
ContentType: "Application/json",
URL: "Default2.aspx/helloworld",//Call WebService's address and method name combination----Wsurl/Method name
Data: "{}",//here is the parameter to pass, in the format data: "{paraname:paravalue}", you will see
DataType: ' JSON ',//webservice will return JSON type

Success:function (Result) {///callback function, result, return value
alert (RESULT.D);
}
});
});
});
Parameters are called
$ (document). Ready (function () {
$ ("#btn2"). Click (function () {
$.ajax ({
Type: "POST",
ContentType: "Application/json",
URL: "Default2.aspx/getwish",
Data: "{value1: ' The things you wish for ', value2: ' All the best ', Value3: ' Bull and Ox ', value4:2009} ',
DataType: ' JSON ',
Success:function (Result) {
alert (RESULT.D);
}
});
});
});
Returns the collection (referenced from the network, which is an indication of the problem)
$ (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 compound 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, both of which can be added to jquery objects before and after Ajax callbacks
But the monitoring of Ajax is global in itself
$ (document). Ready (function () {
$ (' #loading '). Ajaxstart (function () {
$ (this). Show ();
}). Ajaxstop (function () {
$ (this). Hide ();
});
});
When you move the mouse over the effect, multiple elements can be separated by using ","
$ (document). Ready (function () {
$ (' btn '). Hover (function () {
$ (this). addclass (' hover ');
}, function () {
$ (this). Removeclass (' hover ');
});
});
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<input type= "button" id= "Btn1" value= "HelloWorld"/>
<input type= "button" id= "BTN2" value= "Incoming parameters"/>
<input type= "button" id= "Btn3" value= "return collection"/>
<input type= "button" id= "Btn4" value= "return compound type"/>
</div>
<div id= "dictionary" >dictionary
</div>
</form>
</body>

Background. cs file

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 ("I wish you {0}, {1}, {2}" in {3} years, value1, value2, Value3, value4);
}
<summary>
Return collection
</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>
Returns a composite type
</summary>
<returns></returns>
[WebMethod]
public static Class1 GetClass ()
{
return new Class1 {ID = "1", Value = "The Ox of Oxen"};
}
public class Class1
{
public string ID {get; set;}
public string Value {get; set;}
}
}

Use jquery to return the various types of data (String, collection (list<>), Class) returned in JSON data format, why use RESULT.D

Here, we'll talk about JSON in passing.

JSON is simply about JavaScript objects or arrays.

JSON form one: JavaScript object {"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"}

JSON form two: JavaScript array [{"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"},

{"FirstName": "Jason", "LastName": "Hunterwang", "email": "BBBB"}]

Of course, JavaScript arrays and objects can be nested with each other. As in form one, "Brett" can be replaced by a JS array or JS object. What kind of form does Microsoft Ajax return? is the first.

The Microsoft Framework returns a {"D": "Data returned in the background" by default} Here we use the tests in the above example to

If the previous example returns a string type, Firefox debugs as follows

When the list<> type is returned, Firefox debugs as follows

The returned data is also placed in the D attribute of the JS object so that's why we always use RESULT.D to fetch the data returned by the Microsoft framework.

Method One is not commonly used. The general use of more than method two.

Method Two: (Build a general handler i.e.. ashx file)

In this way, it is common for us to manually write the returned JSON-formatted data in the Ashx file back to the foreground.

ASHX you can match JSON format one or JSON format two

Default.aspx page JS code is as follows

$.ajax ({
Type: "POST",

DataType: "JSON",
Success:function (data) {
alert (data.name); Returns the JSON format one (JS object)
/* returned as JSON format II (JS object)
$ (data). Each (function (i) {
alert (data[i].name);
});
*/
}
});

The HANDLER.ASHX 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";
Returns a JS object in JSON format
String data = "{\" name\ ": \" wang\ ", \" age\ ": 25}";
Returns a JSON-formatted two JS array
String data = "[{\" name\ ": \" wang\ ", \" age\ ": 25},{\" name\ ": \" zhang\ ", \" age\ ": 22}]";
Context. Response.Write (data);

public bool IsReusable {
get {
return false;
}
}

}

That's basically the second way, and maybe someone doesn't like to spell a string. So what's the good idea? Microsoft has good support for JSON.

Take the example and say we just need to change the handler.ashx.

The HANDLER.ASHX code is as follows

<%@ WebHandler language= "C #" class= "Handler"%>
Using System;
Using System.Web;
Using System.Collections;
Using System.Collections.Generic; Dictionary<,> Key-value pairs required for the collection
Using System.Web.Script.Serialization; Required for 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;
}
}
}

Asp. NET JavaScriptSerializer provides us with a good way to

Jss. Serialize (Drow) is the conversion of drow dictionary<string, int> (set of keys and values) data type to JSON data format

debugging results such as (the above example is output a key value multi-set is a JSON form one JS object)

What if I want to output JSON form two (JS array)? We'll just have to change one part.

The HANDLER.ASHX 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;
}
}
}

Debug results such as (the above example is the output of the JSON form two JS array)

The basic concept here is about the same. Here's a good example of how to convert Datatabel to JSON format so that the foreground page is called.

is to write a method in Handler.ashx.

    <summary>
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, there are also the conversion of JSON format to Datatabel format, the method is as follows

<summary>
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;
}

We let the returned JSON appear in tabular form.

Then the front page JS as follows

$.ajax ({
Type: "POST",

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"));
}
});

From the above example again two JS points of knowledge

1. Before we take the data inside the JSON if it is returned is an array, it is used data[i].name also can be expressed as data[i]["name"]

2. Traverse the JS object if you want to access all the properties of the JS object.

Success:function (data) {
$ (data). Each (function (i) {
For (key in this)//traverse all properties of the JS object
Alert (Data[i][key]);
You can't switch to Data[i].key. Otherwise the key becomes the attribute instead of the key variable above
});
}

Also has the foreground JSON data to the backstage to parse into Datatabel

In detail Jquery Ajax asynchronously processes JSON data.

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.