Jquery Ajax handles the JSON data asynchronously.

Source: Internet
Author: User
Tags foreach call back goto httpcontext json serialization javascript array
What is called asynchronous, what is Ajax. Let's not talk about XMLHttpRequest. Asynchronous is the Front page Web page Special effectiveness Call back-end method. So that there is no refresh. So called Ajax. Here we talk about two ways
method One: ( Microsoft has its own AJAX framework)
In ASP.net, Microsoft has its own AJAX framework. is to introduce a using System.Web.Services space in the page background. cs file and then define a static method (method preceded by [WebMethod])
[WebMethod]
public static string ABC (string ABC)
{
return ABC;
}
OK, now let's talk about the front desk JS how to deal with the data returned in the background, you can use jquery to process the return of pure html,json,xml and other data. Here we show the returned data has a string, a collection (list<>), a class.
But all return JSON format (JSON lightweight is simpler than XML processing). See how the front desk resolves the data.
The code is as follows:
Front page:
  
  
<%@ Page language= "C #" autoeventwireup= "true" codefile= "default2.asp tutorial X.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 Tutorial" >
. 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" >
No parameter calls
$ (document). Ready (function () {
$ (' #btn1 '). Click (function () {
$.ajax ({
Type: "POST",//Access WebService use POST method request
ContentType: "Application/json",//webservice returns JSON type
URL: "Default2.aspx/helloworld",//Calling WebService address and method name combination----Wsurl/Method name
Data: "{}",//here is the parameter to pass, format is data: "{paraname:paravalue}", you will see the following
DataType: ' JSON ',
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: ' All things are done ', value2: ' Good luck ', value3: ' Cattle and Cows ', value4:2009}",
DataType: ' JSON ',
Success:function (Result) {
alert (RESULT.D);
}
});
});
});
Return collection (referenced from network, very descriptive)
$ (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 in itself a global
$ (document). Ready (function () {
$ (' #loading '). Ajaxstart (function () {
$ (this). Show ();
}). Ajaxstop (function () {
$ (this). Hide ();
});
});
When you move the mouse over the effect, multiple elements, you can use "," separated
$ (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 Files
  
  
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 in {3} years {0}, {1}, {2}", 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 = "Auspicious of the Ox"};
}
public class Class1
{
public string ID {get; set;}
public string Value {get; set;}
}
}
Use jquery to get the types of data returned (String, collection (list<>), Class) returned in JSON data format, why use the RESULT.D
Here, we'll talk about JSON in passing.
JSON is simply a JavaScript object or an array.
JSON form one: JavaScript objects {"FirstName": "Brett", "LastName": "McLaughlin", "email": "AAAA"}
JSON form II: 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. such as "Brett" in form one can be replaced by a JS array or JS object. What is the form of Microsoft's Ajax return? It's the first one.
Microsoft Framework by default returns a {"D": "Background returned data"} Here we use the tests in the above example to
As the example above returns the string type, Firefox debugging is as follows
When the list<> type is returned, Firefox debugging is 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 get the data back from the Microsoft framework.
method is not commonly used. More commonly used or method two.
Method Two: (Build a general processing program i.e.. ashx file)
In this way, we typically return the 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 in JSON format two (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 ":}";
Returns the JSON format two JS array
//string data = "[{" Name ":" Wang "," Age ": 25},{" name ":" Zhang "," Age ": 22}]";
Context. Response.Write (data);
}
Public bool IsReusable {
Get {
return false;

}

}
This is basically the second method, and some people may not like the spelling string. What's the best way to do that? The answer is yes. Microsoft has good support for JSON.
Take an example and say we just need to change Handlerashx.
The HANDLER.ASHX code is as follows
 
   
   
 <%@ webhandler language= "C #" class= "Handler"%> 
using System;
Using System.Web;
using System.Collections; The
using System.Collections.Generic;//dictionary<,> key value is required for the collection
using System.Web.Script.Serialization; The JavaScriptSerializer class requires
public class Handler:ihttphandler {
public void ProcessRequest (HttpContext con Text) {
JavaScriptSerializer JSS = new JavaScriptSerializer ();
Context. Response.ContentType = "Text/plain";
Dictionary<string, string > Drow = new dictionary<string, string > ();
Drow. ADD ("name", "Wang" );
Drow. ADD ("Age", "");
Context. Response.Write (JSS. Serialize (drow));
}
Public bool IsReusable {
Get {
return false;

}
}
ASP. NET JavaScriptSerializer provides a good way for us to
Jss. Serialize (Drow) converts the drow dictionary<string, int> (set of keys and values) data types into JSON data formats
The results of the debugging are as follows (the above example is a JS object that outputs a set of key values-a JSON form one)
If you want to output JSON form two (JS array)? We'll just have to change part of it.
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;
}
}
}
The debug results are as follows (the above example is a JS array that outputs JSON form two)
The basic concepts are almost the same here. One of the most common examples here is how to convert Datatabel to JSON format so that the front page can be invoked.
is to write a method in Handler.ashx.
 
   
   
///<summary>
///DataTable Goto JSON
///</summary>
///<p Aram 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);
}
There is also a way to convert the JSON format to Datatabel format, as follows
  
   
   
<summary>
JSON Goto 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 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"));
}
});
From the above example again to say two JS knowledge points
1. Before we fetch the data in the JSON, if it is an array, it is data[i].name and can be expressed as data[i]["name".
2. If you want to access the JS object said all properties so traverse the JS object.
Success:function (data) {
$ (data). Each (function (i) {
For (key in this)//traversal of all properties of the JS object
Alert (Data[i][key]);
This can't be replaced with Data[i].key, otherwise the key becomes an attribute instead of the key variable above
});
}
There is also the foreground JSON data to the background to resolve into Datatabel
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.