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:
Copy Code code 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" >
<title> Untitled 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" >
No parameter calls
$ (document). Ready (function () {
$ (' #btn1 '). Click (function () {
$.ajax ({
Type: "POST",//Access WebService use POST method request
ContentType: "Application/json",
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 ',//webservice will return 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: ' 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
Copy Code code 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 ("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;}
}
}
Using jquery to return various types of data (string, set (list<>), Class) to the 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
Copy Code code as follows:
$.ajax ({
Type: "POST",
URL: "Handler.ashx",
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
Copy Code code 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 the 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;
}
}
}
This is basically the second method, and there may be people who don't like to spell strings. What's the best way to do that? The answer is yes. 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
Copy Code code as follows:
<%@ WebHandler language= "C #" class= "Handler"%>
Using System;
Using System.Web;
Using System.Collections;
Using System.Collections.Generic; Dictionary<,> key values are required for the collection
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;
}
}
}
Asp. NET in the JavaScriptSerializer provides us with a very good method
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
Copy Code code 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)
So much for the basic concepts. Here's another example of how to convert Datatabel to JSON format so that the front page can be invoked.
is to write a method in Handler.ashx.
Copy Code code as follows:
<summary>
DataTable Turn 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);
}
There are also ways to convert the JSON format to Datatabel format, as follows
Copy Code code 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
Copy Code code 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 all properties of the JS object, then traverse the JS object.
Copy Code code as follows:
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
Here I turn Datatabel into JSON and JSON into Datatabel as an example. Download the following address
SOURCE download
If you're interested in asp.net serialization and deserialization.