×

详谈 Jquery Ajax异步处理Json数据.

作者:Terry2017.02.10来源:Web前端之家浏览:10849评论:0
关键词:JQueryJS
所谓的Ajax.这里我们讲二种方法
方法一:(微软有自带Ajax框架)
在Asp.net里微软有自己的Ajax框架.就是在页面后台.cs文件里引入 using System.Web.Services 空间 然后定义静态方法(方法前加上 [WebMethod])
[WebMethod]
public static string ABC(string ABC)
{
return ABC;
}
好了,现在我们谈谈前台Js怎么处理后台返回的数据吧,可利用Jquery处理返回的纯html,json,Xml等数据.这里我们演示返回返回的数据有string、集合(List<>)、类.
但都返回Json格式(Json轻量级比XML处理起来简单).看看前台是怎么解析这些数据的.
代码如下:
前台页面:
复制代码 代码如下:

<%@ 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() {
$('#btn1').click(function() {
$.ajax({
type: "POST", //访问WebService使用Post方式请求
contentType: "application/json",
url: "Default2.aspx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
data: "{}", //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到
dataType: 'json', //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:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
dataType: 'json',
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: 'json',
success: function(result) {
$(result.d).each(function() {
alert(this);
$('#dictionary').append(this.toString() + " ");
//alert(result.d.join(" | "));
});
}
});
});
});
//返回复合类型
$(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 为用户提供反馈,他们两个方法可以添加给jQuery对象在Ajax前后回调
//但对与Ajax的监控,本身是全局性的
$(document).ready(function() {
$('#loading').ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
});
// 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开
$(document).ready(function() {
$('btn').hover(function() {
$(this).addClass('hover');
}, function() {
$(this).removeClass('hover');
});
});
</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>

后台.cs文件
复制代码 代码如下:

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

利用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;
}
}
}

以上基本上就第二种方法,可能有人不喜欢拼字符串.那有什么好办法呢?答案是有.微软对Json有很好的支持.
拿上例子说我们只要把Handler.ashx改一下就可以了
Handler.ashx 代码如下
复制代码 代码如下:

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

ASP.Net中的JavaScriptSerializer为我们提供了很好的方法

jss.Serialize(drow) 是把drow的Dictionary<string, int> (键和值的集合)数据类型转换成Json数据格式

调试结果如下图 (上面例子是输出了一个键值多集合即一个Json形式一的Js对象)

如果要输出Json形式二(Js数组)呢? 我们也只要改动一部分就了

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

调试结果如下图 (上面例子是输出了Json形式二的Js数组)

 讲到这里基本概念也讲得差不多了. 这里再讲一个够常碰到的例子就是如何把DataTabel转换成Json格式从而好让前台页面调用.

就是在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);
}

其实也有把Json格式转换成DataTabel格式,方法如下
复制代码 代码如下:

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

我们让返回的Json以表格的形式显示出来
那么前台页面JS如下
复制代码 代码如下:

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

由上例子 再讲两个Js知识点
1. 之前我们取Json里面的数据如果是返回的是数组的话是用data[i].name也可表示为data[i]["name"]
2. 如果要访问Js对象的所有属性那么遍历Js对象.
复制代码 代码如下:

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

也有把前台Json数据传到后台后解析成DataTabel
这里我把DataTabel软成Json和Json转成DataTabel写成一个例子.下载地址如下
源码下载
如果大家对asp.net的序列化与反序列化感兴趣想一探究竟的话

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/svg1486656000604.html

网友评论文明上网理性发言已有0人参与

发表评论: