Home > Web Front-end > JS Tutorial > Talk in detail about Jquery Ajax asynchronous processing of Json data._jquery

Talk in detail about Jquery Ajax asynchronous processing of Json data._jquery

WBOY
Release: 2016-05-16 18:02:32
Original
944 people have browsed it

The so-called Ajax. Here we talk about two methods
Method 1: (Microsoft has its own Ajax framework)
In Asp.net, Microsoft has its own Ajax framework. It is to introduce using System in the page background.cs file .Web.Services space and then define static methods (add [WebMethod] before the method)
[WebMethod]
public static string ABC(string ABC)
{
return ABC;
}
Okay, now let’s talk about how the front-end Js handles the data returned by the background. You can use Jquery to process the returned pure html, json, Xml and other data. Here we demonstrate that the returned data includes string, collection (List<> ), class.
But they all return Json format (Json is lightweight and easier to process than XML). Let’s see how the frontend parses these data.
The code is as follows:
Frontend page:

Copy code The code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile ="Default2.aspx.cs" Inherits="Default2" %>
"http://www. w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


Untitled page












dictionary




Backend .cs file
Copy code The 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("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
}
///
/// 返回集合
///

///
///
[WebMethod]
public static List GetArray(int i)
{
List list = new List();
while (i >= 0)
{
list.Add(i--);
}
return list;
}
///
/// 返回一个复合类型
///

///
[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让返回的各类数据(string、集合(List<>)、类)以Json数据格式返回,为什么要用到result.d
这里我们顺带讲下Json
Json简单讲就是Javascript对象或数组.
 Json形式一: javascript对象 { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
Json形式二: javascript数组 [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunterwang", "email": "bbbb"}]
当然javascript 数组和对象可以互相嵌套.如形式一中的"Brett"可以换成一个Js数组或Js对象.那微软的Ajax返回的是哪种形式呢.是第一种.
微软框架默认返回一个 { "d": "后台返回的数据" } 这里我们用以上示例中的测试到得比如
如上例的返回的是string类型的话Firefox调试如下

当返回的是List<>类型的话FireFox调试如下

返回的数据也是放在Js对象中的d属性里面 所以说这就是为什么我们老是用result.d来取微软的框架返回的数据.

方法一不常用.一般用得多的还是方法二.
方法二:(建一个一般处理程序即.ashx文件)
用这种方法一般是我们要在ashx文件里手动写好返回的Json格式的数据返回给前台用
ashx 你可以配成Json格式一或Json格式二
Default.aspx页面Js代码如下

复制代码 代码如下:

$.ajax({
type: "POST",
url: "Handler.ashx",
dataType: "json",
success: function(data){
alert(data.name); //返回的为 Json格式一(Js对象)
/* 返回的为 Json格式二(Js对象)
$(data).each(function(i) {
alert(data[i].name);
});
*/
}
});

Handler.ashx 代码如下
复制代码 代码如下:

<%@ 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";
// 返回的为Json格式一 Js对象
string data = "{"name":"wang","age":25}";
// 返回的为Json格式二 Js数组
//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. So what is a good way? The answer is yes. Microsoft has good support for Json.
Take an example and say that we only need to Just change Handler.ashx
Handler.ashx code is as follows
Copy code Code is as follows:

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Collections;
using System. Collections.Generic; // Dictionary<,> Required for key-value collection
using System.Web.Script.Serialization; //Required for JavaScriptSerializer class
public class Handler: IHttpHandler {
public void ProcessRequest (HttpContext context) {
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.ContentType = "text/plain";
Dictionary drow = new Dictionary( );
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) is to convert drow's Dictionary (a collection of keys and values) data type into Json data format

The debugging result is as shown below (the above example outputs a key-value multi-set, which is a JS object in Json form)

What if we want to output Json form 2 (Js array)? We only need to change part of it

Handler.ashx code is as follows

Copy code 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> _list = new List>();
Dictionary drow = new Dictionary();
drow.Add("name", "Wang");
drow.Add("age", "24");
Dictionary();
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 shown below (The above example is a Js array that outputs Json form 2)

The basic concepts are almost covered here. Here is another frequently encountered example: how to convert DataTabel into Json format so that it can be called by the front page.

Just write a method in Handler.ashx

Copy the code The code is as follows:

///
/// DataTable to Json
///

/// < ;/param>
///
private string Dtb2Json(DataTable dtb)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
ArrayList dic = new ArrayList();
foreach (DataRow row in dtb.Rows)
{
Dictionary drow = new Dictionary();
foreach (DataColumn col in dtb.Columns)
{
drow.Add(col.ColumnName, row[col.ColumnName]);
}
dic.Add(drow);
}
return jss .Serialize(dic);
}

In fact, there is also a way to convert Json format into DataTabel format. The method is as follows
Copy the code The code is as follows:

///
/// Json to DataTable
///

/// ///
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 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 be displayed in the form of a table
Then the front page JS is as follows
Copy the code The code is as follows:

$.ajax({
type: "POST",
url: "Handler.ashx",
dataType: "json",
success: function(data) {
var table = $("
");
for (var i = 0; i < data.length; i ) {
o1 = data[i];
var row = $("");
for (key in o1)
{
var td = $( "");
td.text(o1[key].toString());
td.appendTo(row);}
row.appendTo(table) ;
}
table.appendTo($("#back"));
}
});

Two more Js knowledge points based on the above example
1. Before we retrieved the data in Json, if it returned an array, we used data[i].name, which can also be expressed as data[i]["name"]
2. If you want to access the Js object Then iterate through all the properties of the Js object.
Copy code The code is as follows:

success: function( data){
$(data).each(function(i) {
for(key in this) // Traverse all properties of the Js object
alert(data[i][key]);
//You cannot change it to data[i].key here, otherwise key becomes an attribute instead of the key variable above
});
}

There is also front-end Json data After being passed to the background, it is parsed into DataTabel
Here I soften DataTabel into Json and convert Json into DataTabel as an example. The download address is as follows
Source code download
If you are interested in asp.net If you are interested in serialization and deserialization and want to find out

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template