Home > Web Front-end > JS Tutorial > Detailed discussion on Jquery Ajax asynchronous processing of Json data.

Detailed discussion on Jquery Ajax asynchronous processing of Json data.

高洛峰
Release: 2017-01-12 10:14:19
Original
1185 people have browsed it

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 in the page background .cs file Introduce the using System.Web.Services space and define a static method (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 all return Json format (Json is lightweight and easier to process than XML). See how the frontend parses these data.
The code is as follows:
Frontend 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"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title>无标题页</title> 
<style type="text/css"> 
.hover 
{ 
cursor: pointer; /*小手*/ 
background: #ffc; /*背景*/ 
} 
</style> 
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script> 
<script type="text/javascript"> 
//无参数调用 
$(document).ready(function() { 
$(&#39;#btn1&#39;).click(function() { 
$.ajax({ 
type: "POST", //访问WebService使用Post方式请求 
contentType: "application/json", 
url: "Default2.aspx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名 
data: "{}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到 
dataType: &#39;json&#39;, //WebService 会返回Json类型 
success: function(result) { //回调函数,result,返回值 
alert(result.d); 
} 
}); 
}); 
}); 
//有参数调用 
$(document).ready(function() { 
$("#btn2").click(function() { 
$.ajax({ 
type: "POST", 
contentType: "application/json", 
url: "Default2.aspx/GetWish", 
data: "{value1:&#39;心想事成&#39;,value2:&#39;万事如意&#39;,value3:&#39;牛牛牛&#39;,value4:2009}", 
dataType: &#39;json&#39;, 
success: function(result) { 
alert(result.d); 
} 
}); 
}); 
}); 
//返回集合(引用自网络,很说明问题) 
$(document).ready(function() { 
$("#btn3").click(function() { 
$.ajax({ 
type: "POST", 
contentType: "application/json", 
url: "Default2.aspx/GetArray", 
data: "{i:10}", 
dataType: &#39;json&#39;, 
success: function(result) { 
$(result.d).each(function() { 
alert(this); 
$(&#39;#dictionary&#39;).append(this.toString() + " "); 
//alert(result.d.join(" | ")); 
}); 
} 
}); 
}); 
}); 
//返回复合类型 
$(document).ready(function() { 
$(&#39;#btn4&#39;).click(function() { 
$.ajax({ 
type: "POST", 
contentType: "application/json", 
url: "Default2.aspx/GetClass", 
data: "{}", 
dataType: &#39;json&#39;, 
success: function(result) { 
$(result.d).each(function() { 
//alert(this); 
$(&#39;#dictionary&#39;).append(this[&#39;ID&#39;] + " " + this[&#39;Value&#39;]); 
//alert(result.d.join(" | ")); 
}); 
} 
}); 
}); 
}); 
//Ajax 为用户提供反馈,他们两个方法可以添加给jQuery对象在Ajax前后回调 
//但对与Ajax的监控,本身是全局性的 
$(document).ready(function() { 
$(&#39;#loading&#39;).ajaxStart(function() { 
$(this).show(); 
}).ajaxStop(function() { 
$(this).hide(); 
}); 
}); 
// 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开 
$(document).ready(function() { 
$(&#39;btn&#39;).hover(function() { 
$(this).addClass(&#39;hover&#39;); 
}, function() { 
$(this).removeClass(&#39;hover&#39;); 
}); 
}); 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<input type="button" id="btn1" value="HelloWorld"/> 
<input type="button" id="btn2" value="传入参数"/> 
<input type="button" id="btn3" value="返回集合"/> 
<input type="button" id="btn4" value=" 返回复合类型"/> 
</div> 
<div id="dictionary">dictionary 
</div> 
</form> 
</body> 
</html>
Copy after login

Backend .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("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4); 
} 
/// <summary> 
/// 返回集合 
/// </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> 
/// 返回一个复合类型 
/// </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; } 
} 
}
Copy after login

Use Jquery to return various types of data (string, collection (List<>), class) in Json data format. Why use result. d
Here we will talk about Json
Json is simply a Javascript object or array.
Json form 1: javascript object { "firstName": "Brett", "lastName": "McLaughlin", "email ": "aaaa" }
Json form 2: javascript array [{ "firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunterwang", "email": "bbbb"}]
Of course, javascript arrays and objects can be nested in each other. For example, "Brett" in form 1 can be replaced with a Js array or Js Object. So what form does Microsoft's Ajax return? It's the first one.
Microsoft framework returns a { "d": "Data returned by the background" } by default. Here we use the test in the above example to get something like
As in the above example, if the string type is returned, the Firefox debugging is as follows

Detailed discussion on Jquery Ajax asynchronous processing of Json data.

When the List<> type is returned, the Firefox debugging is as follows

Detailed discussion on Jquery Ajax asynchronous processing of Json data.

The returned data is also placed in the d attribute in the Js object, so this is why we always use result.d to get the data returned by the Microsoft framework.

Method 1 It is not commonly used. Method 2 is generally used more often.
Method 2: (Build a general processing program, i.e. .ashx file)
Using this method usually means that we have to manually write the returned Json in the ashx file. The data in the format is returned to the front desk for use
ashx You can configure it into Json format one or Json format two
Default.aspx page Js code is as follows

$.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); 
}); 
*/ 
} 
});
Copy after login

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"; 
// 返回的为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; 
} 
} 
}
Copy after login

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.
Taking the example, we only need to use Handler. Just change ashx.
Handler.ashx code is as follows

<%@ WebHandler Language="C#" Class="Handler" %> 
using System; 
using System.Web; 
using System.Collections; 
using System.Collections.Generic; // Dictionary<,> 键值对集合所需 
using System.Web.Script.Serialization; //JavaScriptSerializer 类所需 
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; 
} 
} 
}
Copy after login

JavaScriptSerializer in ASP.Net provides us with a good method

jss.Serialize(drow) is to change drow The Dictionary (a collection of keys and values) data type is converted into Json data format

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

Detailed discussion on Jquery Ajax asynchronous processing of Json data.

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

<%@ 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; 
} 
} 
}
Copy after login

The debugging result is as shown below (the above example is a Js array that outputs Json form 2)

Detailed discussion on Jquery Ajax asynchronous processing of Json data.

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

is to write a method in Handler.ashx

/// <summary> 
/// DataTable转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); 
}
Copy after login

In fact, there is also a way to convert Json format into DataTabel format, the method is as follows

/// <summary> 
/// Json转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; 
}
Copy after login

We let the returned Json be displayed in the form of a table
Then the front page JS is as follows

$.ajax({ 
type: "POST", 
url: "Handler.ashx", 
dataType: "json", 
success: function(data){ 
var table = $("<table border=&#39;1&#39;></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")); 
} 
});
Copy after login

Let’s talk about two more Js knowledge points from the above example
1. Before we took the data in Json, if the returned array was data[i].name, it can also be expressed as data[i]["name"]
2. If you want to access all the Js objects Attributes then traverse the Js object.

success: function(data){ 
$(data).each(function(i) { 
for(key in this) // 遍历Js对象的所有属性 
alert(data[i][key]); 
//这里就不能换成 data[i].key 否则key成了属性而不是上面的key变量 
}); 
}
Copy after login

There is also a way to pass the front-end Json data to the background and parse it into a DataTabel

For more details on Jquery Ajax asynchronous processing of Json data. For related articles, please pay attention to the PHP Chinese website!

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