查看: 7047|回复: 0
打印 上一主题 下一主题

探索AJAX中的消息传输模式(二)

[复制链接]
跳转到指定楼层
1#
发表于 2008-6-26 09:59:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
台州网址导航
在上一篇《探索AJAX中的消息传输模式(一) 》一文中,我主要介绍了普通字符串(Plain-text string)和XML格式的传输模式,然而在实际的开发应用中,这两种方法基本上可以足够应付我们的需求了,不过在对于复杂的对象传输的时候,采用上面所介绍的这两种传输模式有点显得不理想。于此,本文将结合《探索AJAX中的消息传输模式(一) 》再介绍一种轻量级的数据交换格式JSON(JavaScript Object Notation) ,这是一种JavaScrpt自己的一种用来描述对象的方法,JSON从某个角度看可以说是XML的替代品。
      在怎么使用JSON来进行数据传输之前,我们先来看看几个简单的JSON语法,为不熟悉JSON且想看本文的朋友打下基础。JSON和XML一样也是一种简单文本格式。相对于XML,它更加易读、更便于肉眼检查。在语法的层面上,JSON与其他格式的区别是在于分隔数据的字符,JSON中的分隔符限于单引号、小括号、中括号、大括号、冒号和逗号。下面是一个JSON有效负载:

{"UserID":"0001","UserName":"ZhangSan","UserAge":"22"}
     看起来是不是很简单,键与值一一对应(Key----Value),下面我们看看一个复杂点的JSON有效负载:

1{Employees:[
2       {"EmployeeID":"1","LastName":"Davolio","City":"Seattle","Country":"USA"},
3       {"EmployeeID":"2","LastName":"Fuller","City":"Tacoma","Country":"USA"}
4           ]
5}   
     从上面的JSON可以很清晰的看出,在Employees这个对象里包含有两条数据,我们将其用XML改写,如下:  1<?xml version='1.0' ?>
2<Employees>
3  <Employee>
4     <EmployeeID>1</EmployeeID>
5     <LastName>Davolio</LastName>
6     <City>Seattle</City>
7     <Country>USA</Country>
8  </Employee>
9  <Employee>
10    <EmployeeID>2</EmployeeID>
11    <LastName>Fuller</LastName>
12    <City>Tacoma</City>
13    <Country>USA</Country>
14  </Employee>
15<Employees>
      关于JSON更详细的使用和语法格式请查看相关资料,这里我推荐一个网站(http://www.json.org/)。也可以在在园里搜索下园内前辈们的文章,Truly的《深入浅出JSON 》这篇文章就介绍了JSON,个人感觉介绍的很细致。

     上面说了这么多,我们还是用一个示例来演示下JSON的使用,要不就成了纸上谈兵了。 本文的是《探索AJAX中的消息传输模式(一) 》的续篇,示例代码还是建立在此文的基础上,在WebService里添加一新方法提供根据员工编号(EmployeeID)查询小于等于(<=)该编号的所用员工信息:

[WebMethod]
public string GetEmployeeWithJson(int id)
{
    //查询出EmployeeID,LastName,City,Country四个字段
    DataTable dt = DataAccess.GetEmployees(id);
    StringBuilder json = new StringBuilder();
    json.Append("{Employees:[");

    int i = 0;
    string result = string.Empty;
    foreach (DataRow row in dt.Rows)
    {
        json.Append("{");
        json.Append(@"""EmployeeID"":""" + row["EmployeeID"] + @""",");
        json.Append(@"""LastName"":""" + row["LastName"] + @""",");
        json.Append(@"""City"":""" + row["City"] + @""",");
        json.Append(@"""Country"":""" + row["Country"] + @"""}");

        if (++i == dt.Rows.Count)
        {
            json.Append("}]");
        }
        json.Append(",");
    }
    json.Append("}");
    result = json.ToString().Remove(json.Length - 2, 1);  //移除","
    result = result.Remove(result.Length - 3, 1);  //移除"}"
    return result;
}DataAccess.GetEmpoyees(int id)方法定义
1public static DataTable GetEmployees(int id)
2{
3    string cmdText = "select EmployeeID,LastName,City,Country from Employees";
4    cmdText += " where EmployeeID <= " + id;
5    return Exce(cmdText); //执行SQL返回DataTable
6}
     这里也许大家会有所疑问,为什么这方法后面要移除一个","和"}",这是在上面动态构造JSON字符串的时候多出来的,如果不移除方法的返回值则是下面这样:
    为了使在客户端通过JavaScript能够正确的解吸此JSON,在返回值后面多出的一个","和"}"是必须去掉的,如下:
    到此,服务端的工作算准备完毕,下面看看客户端是如何实现,首先为aspx页面提供ScriptManager控件,然后引入WebService以便在客户端调用WebService里的方法: 1<asp:ScriptManager ID="ScriptManager1" runat="server">
2  <Services>
3    <asp:ServiceReference Path="MessageWebService.asmx" />
4  </Services>
5</asp:ScriptManager>
    在提供一个下来列表控件来让用户选择员工编号,这里通过设置默认值(在实际开发应用中可能会从数据库里读取数据,这里只是为了做程序演示),通过一个按扭来发送请求,将结果显示在div(resultEmployee)里:
1请选择员工编号范围小于(&lt;)<asp:DropDownList ID="ddlEmployeeID" runat="server">
2    <asp:ListItem>1</asp:ListItem>
3    <asp:ListItem>2</asp:ListItem>
4    <asp:ListItem>3</asp:ListItem>
5    <asp:ListItem>4</asp:ListItem>
6    <asp:ListItem>5</asp:ListItem>
7    <asp:ListItem>6</asp:ListItem>
8    <asp:ListItem>7</asp:ListItem>
9    <asp:ListItem>8</asp:ListItem>
10</asp:DropDownList>
11
12<input id="Query" type="button" value="查 询" /><br /><hr />
13<div id="resultEmployee"></div>
    同样,我们需要初始化客户端对控件的引用,以及为按扭添加执行事件:  1var ddlEmployeeID;
2var divResult;
3var buttonQuery;
4   
5function pageLoad()
6{
7   ddlEmployeeID = $get("<% = ddlEmployeeID.ClientID %>");
8   divResult = $get("resultEmployee");
9   buttonQuery = $get("Query");
10   $addHandler(buttonQuery,"click",onButtonClicked);
11   onButtonClicked(null);
12}
     当点击按扭的时候就触发click事件,调用onButtonClicked方法,执行调用WebService里的方法: 1function onButtonClicked(eventElement)
2{
3    //取得选择的员工ID
4     var employeeID = ddlEmployeeID.options[ddlEmployeeID.selectedIndex].value;
5    //调用WebService获取数据
6    MessageWebService.GetEmployeeWithJson(employeeID,onJsonCallBack);
7}
    以异步的方式向服务端发起请求,把employeeID做为参数传递到服务器端,通过onJsonCallBack回调方法来处理返回的数据,如下所示:  1//根据返回的数据动态构造html表格
2var html = new Sys.StringBuilder();
3html.append("<table width='460px' cellspacing='1' cellpadding='2' border='0' bgcolor='#999999'>");
4html.append("<tr>");
5html.append("<td bgcolor='gold' align='center'><b>EmployeeID</b></td>");
6html.append("<td bgcolor='gold' align='center'><b>LastName</b></td>");
7html.append("<td bgcolor='gold' align='center'><b>City</b></td>");
8html.append("<td bgcolor='gold' align='center'><b>Country</b></td>");
9html.append("</tr>");
10      
11for (var i=0;i< data.Employees.length;i++)
12{  
13    html.append("<tr>");
14    html.append("<td bgcolor='white'>"+data.Employees["EmployeeID"]+"</td>");
15    html.append("<td bgcolor='white'>"+data.Employees.LastName+"</td>");
16    html.append("<td bgcolor='white'>"+data.Employees.City+"</td>");
17    html.append("<td bgcolor='white'>"+data.Employees.Country+"</td>");
18    html.append("</tr>");
19}
20html.append("</table>");
21resultEmployee.innerHTML = html.toString();客户端的完整代码
1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxMessageJson.aspx.cs" Inherits="AjaxMessageJson" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<html xmlns="http://www.w3.org/1999/xhtml" >
6<head runat="server">
7    <title>无标题页</title>
8</head>
9<body>
10    <form id="form1" runat="server">
11    <div>
12        <asp:ScriptManager ID="ScriptManager1" runat="server">
13          <Services>
14            <asp:ServiceReference Path="MessageWebService.asmx" />
15          </Services>
16        </asp:ScriptManager>
17    <%--d--%>
18    </div>
19        请选择员工编号范围小于(&lt;)<asp:DropDownList ID="ddlEmployeeID" runat="server">
20            <asp:ListItem>1</asp:ListItem>
21            <asp:ListItem>2</asp:ListItem>
22            <asp:ListItem>3</asp:ListItem>
23            <asp:ListItem>4</asp:ListItem>
24            <asp:ListItem>5</asp:ListItem>
25            <asp:ListItem>6</asp:ListItem>
26            <asp:ListItem>7</asp:ListItem>
27            <asp:ListItem>8</asp:ListItem>
28        </asp:DropDownList>
29        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
30        <input id="Query" type="button" value="查 询" /><br /><hr />
31        <div id="resultEmployee"></div>
32    </form>
33   
34    <script type="text/javascript">
35   
36    var ddlEmployeeID;
37    var divResult;
38    var buttonQuery;
39   
40    function pageLoad()
41    {
42       ddlEmployeeID = $get("<% = ddlEmployeeID.ClientID %>");
43       divResult = $get("resultEmployee");
44       buttonQuery = $get("Query");
45       $addHandler(buttonQuery,"click",onButtonClicked);
46       onButtonClicked(null);
47    }
48   
49    function onButtonClicked(eventElement)
50    {
51       //取得选择的员工ID
52       var employeeID = ddlEmployeeID.options[ddlEmployeeID.selectedIndex].value;
53       //调用WebService获取数据
54       MessageWebService.GetEmployeeWithJson(employeeID,onJsonCallBack);
55    }
56   
57    function onJsonCallBack(text)
58    {
59       var data = eval("data="+text);         
60       //服务端的WebService返回的是一个JSON字符串,上面的赋值后data的数据实际就等同于下面的定义            
61       //var data = {Employees:[{"EmployeeID":"1","LastName":"Davolio","City":"Seattle","Country":"USA"},
62       //            {"EmployeeID":"2","LastName":"Fuller","City":"Tacoma","Country":"USA"},
63       //            {"EmployeeID":"3","LastName":"Leverling","City":"Kirkland","Country":"USA"}]};
64       //
65      
66       //根据返回的数据动态构造html表格
67       var html = new Sys.StringBuilder();
68       html.append("<table width='460px' cellspacing='1' cellpadding='2' border='0' bgcolor='#999999'>");
69       html.append("<tr>");
70       html.append("<td bgcolor='gold' align='center'><b>EmployeeID</b></td>");
71       html.append("<td bgcolor='gold' align='center'><b>LastName</b></td>");
72       html.append("<td bgcolor='gold' align='center'><b>City</b></td>");
73       html.append("<td bgcolor='gold' align='center'><b>Country</b></td>");
74       html.append("</tr>");
75      
76       for (var i=0;i< data.Employees.length;i++)
77       {  
78          html.append("<tr>");
79          html.append("<td bgcolor='white'>"+data.Employees["EmployeeID"]+"</td>");
80          html.append("<td bgcolor='white'>"+data.Employees.LastName+"</td>");
81          html.append("<td bgcolor='white'>"+data.Employees.City+"</td>");
82          html.append("<td bgcolor='white'>"+data.Employees.Country+"</td>");
83          html.append("</tr>");
84       }
85       html.append("</table>");
86       resultEmployee.innerHTML = html.toString();
87    }
88    </script>
89</body>
90</html>

    如上处理,如果服务器端无数据返回则在客户端页面上只输出表头信息,如果有数据返回,则动态的构造了表格并显示在页面上,如下:



由于前段时间写文章的时候没对示例进行解说,今天特改动了下文章。本文就介绍于此,欢迎大家拍砖指正,谢谢!!
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 转播转播 分享分享 分享淘帖
台州维博网络(www.tzweb.com)专门运用PHP+MYSQL/ASP.NET+MSSQL技术开发网站门户平台系统等。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

网站推广
关于我们
  • 台州朗动科技(Tzweb.com)拥有多年开发网站平台系统门户手机客户端等业务的成功经验。主要从事:政企网站,系统平台,微信公众号,各类小程序,手机APP客户端,浙里办微应用,浙政钉微应用、主机域名、虚拟空间、后期维护等服务,满足不同企业公司的需求,是台州地区领先的网络技术服务商!

Hi,扫描关注我

Copyright © 2005-2026 站长论坛 All rights reserved

Powered by 站长论坛 with TZWEB Update Techonolgy Support

快速回复 返回顶部 返回列表