詳談 Jquery Ajax異步處理Json數(shù)據(jù).
方法一:(微軟有自帶Ajax框架)
在Asp.net里微軟有自己的Ajax框架.就是在頁面后臺.cs文件里引入 using System.Web.Services 空間 然后定義靜態(tài)方法(方法前加上 [WebMethod])
[WebMethod]
public static string ABC(string ABC)
{
return ABC;
}
好了,現(xiàn)在我們談?wù)勄芭_Js怎么處理后臺返回的數(shù)據(jù)吧,可利用Jquery處理返回的純html,json,Xml等數(shù)據(jù).這里我們演示返回返回的數(shù)據(jù)有string、集合(List<>)、類.
但都返回Json格式(Json輕量級比XML處理起來簡單).看看前臺是怎么解析這些數(shù)據(jù)的.
代碼如下:
前臺頁面:
<%@ 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">
//無參數(shù)調(diào)用
$(document).ready(function() {
$('#btn1').click(function() {
$.ajax({
type: "POST", //訪問WebService使用Post方式請求
contentType: "application/json",
url: "Default2.aspx/HelloWorld", //調(diào)用WebService的地址和方法名稱組合 ---- WsURL/方法名
data: "{}", //這里是要傳遞的參數(shù),格式為 data: "{paraName:paraValue}",下面將會看到
dataType: 'json', //WebService 會返回Json類型
success: function(result) { //回調(diào)函數(shù),result,返回值
alert(result.d);
}
});
});
});
//有參數(shù)調(diào)用
$(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);
}
});
});
});
//返回集合(引用自網(wǎng)絡(luò),很說明問題)
$(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(" | "));
});
}
});
});
});
//返回復(fù)合類型
$(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前后回調(diào)
//但對與Ajax的監(jiān)控,本身是全局性的
$(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="傳入?yún)?shù)"/>
<input type="button" id="btn3" value="返回集合"/>
<input type="button" id="btn4" value=" 返回復(fù)合類型"/>
</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>
/// 返回一個復(fù)合類型
/// </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讓返回的各類數(shù)據(jù)(string、集合(List<>)、類)以Json數(shù)據(jù)格式返回,為什么要用到result.d
這里我們順帶講下Json
Json簡單講就是Javascript對象或數(shù)組.
Json形式一: javascript對象 { "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
Json形式二: javascript數(shù)組 [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunterwang", "email": "bbbb"}]
當然javascript 數(shù)組和對象可以互相嵌套.如形式一中的"Brett"可以換成一個Js數(shù)組或Js對象.那微軟的Ajax返回的是哪種形式呢.是第一種.
微軟框架默認返回一個 { "d": "后臺返回的數(shù)據(jù)" } 這里我們用以上示例中的測試到得比如
如上例的返回的是string類型的話Firefox調(diào)試如下
當返回的是List<>類型的話FireFox調(diào)試如下
返回的數(shù)據(jù)也是放在Js對象中的d屬性里面 所以說這就是為什么我們老是用result.d來取微軟的框架返回的數(shù)據(jù).
方法一不常用.一般用得多的還是方法二.
方法二:(建一個一般處理程序即.ashx文件)
用這種方法一般是我們要在ashx文件里手動寫好返回的Json格式的數(shù)據(jù)返回給前臺用
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數(shù)組
//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> (鍵和值的集合)數(shù)據(jù)類型轉(zhuǎn)換成Json數(shù)據(jù)格式
調(diào)試結(jié)果如下圖 (上面例子是輸出了一個鍵值多集合即一個Json形式一的Js對象)
如果要輸出Json形式二(Js數(shù)組)呢? 我們也只要改動一部分就了
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;
}
}
}
調(diào)試結(jié)果如下圖 (上面例子是輸出了Json形式二的Js數(shù)組)
講到這里基本概念也講得差不多了. 這里再講一個夠常碰到的例子就是如何把DataTabel轉(zhuǎn)換成Json格式從而好讓前臺頁面調(diào)用.
就是在Handler.ashx寫上一個方法
/// <summary>
/// DataTable轉(zhuǎn)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格式轉(zhuǎn)換成DataTabel格式,方法如下
/// <summary>
/// Json轉(zhuǎn)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. 之前我們?nèi)son里面的數(shù)據(jù)如果是返回的是數(shù)組的話是用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數(shù)據(jù)傳到后臺后解析成DataTabel
這里我把DataTabel軟成Json和Json轉(zhuǎn)成DataTabel寫成一個例子.下載地址如下
源碼下載
如果大家對asp.net的序列化與反序列化感興趣想一探究竟的話
- jQuery中ajax請求后臺返回json數(shù)據(jù)并渲染HTML的方法
- 基于jQuery的AJAX和JSON實現(xiàn)純html數(shù)據(jù)模板
- JQuery的ajax獲取數(shù)據(jù)后的處理總結(jié)(html,xml,json)
- JQuery處理json與ajax返回JSON實例代碼
- jquery的ajax異步請求接收返回json數(shù)據(jù)實例
- jQuery Ajax異步處理Json數(shù)據(jù)詳解
- jQuery中使用Ajax獲取JSON格式數(shù)據(jù)示例代碼
- jquery序列化form表單使用ajax提交后處理返回的json數(shù)據(jù)
- 跨域請求之jQuery的ajax jsonp的使用解惑
- jquery ajax跨域解決方法(json方式)
- jQuery+Ajax+js實現(xiàn)請求json格式數(shù)據(jù)并渲染到html頁面操作示例
相關(guān)文章
jquery實現(xiàn)的元素的left增加N像素 鼠標移開會慢慢的移動到原來的位置
鼠標移動上去,元素的left增加N像素,鼠標移開會慢慢的移動到原來的位置2010-03-03jQuery仿Flash上下翻動的中英文導(dǎo)航菜單實例
這篇文章主要介紹了jQuery仿Flash上下翻動的中英文導(dǎo)航菜單,實例分析了jQuery實現(xiàn)Flash反動特效的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03jQuery綁定事件方法及區(qū)別(bind,click,on,live,one)
這篇文章主要介紹了jq綁定事件方法及區(qū)別,通過五種綁定方式使用bind()進行操作,并和one()進行區(qū)分,需要的朋友可以參考下2017-08-08Eclipse下jQuery文件報錯出現(xiàn)錯誤提示紅叉
工程中加入jquery.xx.js文件,發(fā)現(xiàn)該文件出現(xiàn)錯誤提示(紅×),但使用Eclipse 3.7以前的版本就不會出現(xiàn)這種提示,下面有個不錯的解決方法,大家可以參考下2014-01-01jQuery實現(xiàn)的一個tab切換效果內(nèi)部還嵌有切換
這篇文章主要介紹了jQuery實現(xiàn)的一個tab切換效果,它的特色是內(nèi)部還嵌有切換,需要的朋友可以參考下2014-08-08