现在的位置: 首页 > 综合 > 正文

在asp.net2.0中使用Jquery调用Web Service[附源代码]

2012年08月23日 ⁄ 综合 ⁄ 共 7142字 ⁄ 字号 评论关闭

代码:/Files/zhuqil/JSONDemo.zip

介绍:

      我们都知道,默认情况下,一个asp.net Web Service 返回的数据格式是XML的,处理XML数据总是会花费一些开销,最近,另外一种JSON的格式非常流行并且能够克服这些问题。从.NET 3.5起,微软在ASP.NET 3.5提供了处理JSON内置功能,但是现在很多应用程序还是运行在Asp.net2.0下。我将向你显示如何简单的返回JSON格式的数据从一个Web Service上,并使用Jquery来处理他,Jquery是一个非常流行的,轻量级的Javascript类库。

背景:

     有些时候,我开发的项目它包括大量的Web Service 访问。处理XML数据花费的时间大大的超过了我们预期的时间,所以我决定使用Json格式来返回数据。它非常的轻量级,而且在客户端非常容易被javascript处理。例如:我们有这样以个实体类“Employee”,它包括五个字段:"Name", "Company", "Address", "Phone", and "Country". 当你以XML格式从 Web Service 返回时,你将得到的这样的数据:

当以Json格式返回时,你将得到下面的数据:

如果你比较两个值,你就会发现,JSON格式的返回的仅仅是字符串,而且没有XML格式头结点的花销。所以您需要做的是字符串的处理,它们都以键值对的形式存在。往下讲述之前,我想在说明一下JSON(JavaScript Object Notation).它是一种轻量级的数据交互格式,这是一个文本格式,使得它完全独立于语言。JSON是建立在两种数据结构之上:

一种键值对的集合,像 Dictionary, Hashtable 等等

一个有序的对象,像array, list, sequence 等等

想了解更多的Json,可以去 json.org.

需求要的软件:

  • Visual Studio 2005/2008 or Visual Studio 2005/2008 Express Edition
  • ASP.NET 2.0 AJAX Extensions 1.0

    你也能使用 Microsoft Web Platform Installer 2.0,在这里,能安装所有需要的基于web开发的软件,这还包括IIS。

    现在,让我们讨论如何实施解决方案。

    安装 ASP.NET AJAX Extensions 1.0. 默认的安装路径为 “Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025”. 这个路径下面的结构如下:

    System.Web.Extension.dll 是实现这些功能主要使用的dll文件。你也可以安装:Visual Studio 2008 Template for AJAX Extension.

    实现:

    建立一个简单ASP.NET Web Service 页面并且命名为: JSONDemo

    Web Service 创建以后,将其改名为:JSON ,然后添加System.Web.Extensions.dll引用,添加引用之后,我们的程序应该如下图所示:

    配置Web.Config

    为了使用这个,我们需要在<system.web>下面使用下面的代码段,添加一个ScriptHandlerFactory的HttpHandler节点.

     

    代码

    <httphandlers>
     
    <remove verb="*" path="*.asmx"></remove>
      
    <add verb="*" path="*.asmx" 
         type
    ="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions,
         Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35">
     </add>
    </httphandlers>

     

    添加实体类:

    在我们的Web Service中添加一个名字为“Employee ”的实体类。

     

    代码

    public class Employee
    {
        
    public string Name { getset; }
        
    public string Company { getset; }
        
    public string Address { getset; }
        
    public string Phone { getset; }
        
    public string Country { getset; }
    }

     

     

    配置ASMX Web Service:

    如果你使用 object browser打开system.web.extension.dll ,你就会发现下面的命名空间:

    现在我们需要添加命名空间:System.Web.Script.ServicesSystem.Web.Script.Serialization ,using 像下面所示:

     

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Services;
    using System.Web.Script.Services;
    using System.Web.Script.Serialization;

     现在我们添加 ScriptService ,它是System.Web.Script.Services 命名空间下面的部分类属性。使用这个属性,使得javascript很容易的访问Web Service 。这个属性致使 Web Service 能接受 JSON 格式的输入参数和以Json格式作为返回类型。这样完全不用解析XML了。在添加ScriptService 属性之后,再添加ScriptMethod(ResponseFormat = ResponseFormat.Json)来返回JSON 格式的数据。Web Service 默认的就有ScriptService属性装饰,以JSON格式返回而不是XML。所以你甚至不需要添加ResponseFormat.Json属性。但如果你需要你的Web Service的方法以XML格式返回,你必须具体使用ScriptMethod(ResponseFormat = ResponseFormat.Xml)来告诉web service ,在我的例子,我仅仅只为澄清此属性。

    当上面的步骤完成以后,你的代码应该如下所示:

    代码

    namespace JSONDemo
    {
        
    /// <summary>
        
    /// Summary description for Service1
        
    /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo 
    = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(
    false)]
        [ScriptService]
        
    public class JSONService : System.Web.Services.WebService
        {

            [WebMethod]
            [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
            
    public string TestJSON()
            {
                Employee[] e 
    = new Employee[2];
                e[
    0= new Employee();
                e[
    0].Name = "Ajay Singh";
                e[
    0].Company = "Birlasoft Ltd.";
                e[
    0].Address = "LosAngeles California";
                e[
    0].Phone = "1204675";
                e[
    0].Country = "US";
                e[
    1= new Employee();
                e[
    1].Name = "Ajay Singh";
                e[
    1].Company = "Birlasoft Ltd.";
                e[
    1].Address = "D-195 Sector Noida";
                e[
    1].Phone = "1204675";
                e[
    1].Country = "India";
                
    return new JavaScriptSerializer().Serialize(e);
            }
            [WebMethod]
            [ScriptMethod(ResponseFormat 
    = ResponseFormat.Xml)]
            
    public Employee[] TestXML()
            {
                Employee[] e 
    = new Employee[2];
                e[
    0= new Employee();
                e[
    0].Name = "Ajay Singh";
                e[
    0].Company = "Birlasoft Ltd.";
                e[
    0].Address = "LosAngeles California";
                e[
    0].Phone = "310-235-1535";
                e[
    0].Country = "US";
                e[
    1= new Employee();
                e[
    1].Name = "Ajay Singh";
                e[
    1].Company = "Birlasoft Ltd.";
                e[
    1].Address = "D-195 Sector Noida";
                e[
    1].Phone = "120-467500";
                e[
    1].Country = "India";
                
    return e;
            }
        }
    }

     

    现在,我们已经准备好了我们的Web Service了,你能够直接在浏览器中测试这个Web Service,我将会向你展示如何在一个HTML页面中使用Jquery来调用这个Web Service。

    But if you don’t want to use jQuery and want to use the Microsoft ASP.NET AJAX Script Manager to call the Web Service from client-side, a JavaScript proxy class is generated. You can see the JavaScript proxy class by using the "/js" parameter after the .asmx page.

    但是如果你在客户端不想使用jQuery而是想使用Microsoft ASP.NET AJAX Script Manager 来访问Web Service ,一个Javascript的代理类将会被产生。你在 .asmx 页面后面添加“/js” 查看这个代理类。例如:http://localhost/jsondemo/JSON.asmx/js.

    使用Jquery调用Web Service

    下面是使用Jquery调用Web Service的代码:

     

    代码

    function testJson() {
        $.ajax({
            type: 
    "POST",
            url: 
    "JSON.asmx/TestJSON",
            data: 
    "{}",
            contentType: 
    "application/json; charset=utf-8",
            dataType: 
    "json",
            success: 
    function(msg) {
                
    var data = eval("(" + msg + ")");
                
    var t = "<table border=1> <tr>" +
                  
    "<td> <strong>Name</strong></td> <td> " +
                  
    "<strong>Company</strong></td> <td> " +
                  
    "<strong>Address</strong></td> <td> " +
                  
    "<strong>Phone</strong></td> <td> " +
                  
    "<strong>Country</strong></td> </tr> ";
                jQuery.each(data, 
    function(rec) {
                    t 
    = t + " <tr> <td> " + this.Name + "</td> <td> " +
                        
    this.Company + "</td> <td> " + this.Address +
                         
    "</td> <td> " + this.Phone + 
                         
    "</td> <td> " + this.Country + 
                         
    "</td> </tr> ";
                });

                t = t + " </table> ";

                $("#jsonDiv").html(t);
            },
            error: 
    function(msg) {

            }
        });
    };

     

     

    $.ajax()是一个jQuery的方法来使用Ajax调用的.它需要几个变量,这几个变量的描述如下:

  • type: 当调用Web Service,你将总是使用 “POST”.
  • url: the Web Service URL 加上web method 名字. 在上面的例子中, “JSON.asmx” 是webservice的URL , TestJSON 是 web method.
  • data: 用来传递一个参数给web service的方法.
  • contentType: 当调用一个 JSON Web Service,你总是需要做这样的设置:"application/json; charset=utf-8".
  • dataType:你需要设置的Web Service 调用的基本的数据类型, ; 对于一个JSON 调用, 你应该设置为:"json".
  • success: 这里,我们定义了一个函数,当成功处理之后才会被调用,上面的例子中,我定义了一个异步的函数来处理Web Serivice 的返回值, 你也能够像下面一样定
    function (msg) { var data = eval("(" + msg + ")"); 
        ProcessWebServiceResult(data) 
    //javascript function }

     

     在ASP.NET 2.0中,和ASP.NET 3.5相比较调用Web Service处理是不同的,这是因为我们使用了eval function。如果使用 ASP.NET 3.5,你将会简单的使用 msg.d,d是一个消息反应,其中包含的内容属性,还有一点我想解释关于function (msg)的声明,参数msg能命名成什么你想要的名字.jQuery的所做的是什么,它分配在此参数消息的反应,然后你可以相应地处理它。

     

  • error: 这里,如果返回错误,你能使用异步函数或者一个分离函数来处理这个错误。

    这儿是一个输出,但你点击JSON 按钮的时候:

     

    总结:

    从上述所有,你能看出实现一个在ASP.NET 2.0中使用 JSON Web Service 是如此简单,并在一个HTML页面中去使用Jquery调用它。只是写这篇文章的理由,当我开始做这项工作,我面临着很多问题,因为我没有找到在一个地方的所有信息。我附加一个完整的例子,来说明我上面所述。在这个项目中,还包括“System.Web.Extensions.dll”,所以你甚至不需要下载 ASP.NET AJAX 1.0 Extensions ,如果你想创建一个JSON的Web Service。但是如果在客户端,你想使用ASP.NET AJAX 来代替 jQuery的处理,那么你就需要下载。在这里,我希望这篇文章可以帮助你了解的一些概念。感谢所有的反馈。

    本文翻译:http://www.codeproject.com/KB/webservices/jsonwebservice.aspx

  • 抱歉!评论已关闭.