.NET ajax调用WebService

来源:互联网 发布:最新淘宝删除中差评 编辑:程序博客网 时间:2024/04/29 19:19

http://www.cnblogs.com/dflying/archive/2007/06/05/771471.html

基础使用

1        新建一个解决方案,右键解决方案名称选择“添加新建网站”,新建一个asp.net网站WebSite1,右键Website1,选择“添加新项—Web服务”,添加一个Web服务WebService1。则在跟目录下生成WebService1.asmxApp_Code文件夹中生成WebService1.cs。在WebService1.cs文件中,已经生成一个web方法HelloWorld如下:

   /// <summary>

   /// 返回字符串

   /// </summary>

   /// <returns></returns>

   [WebMethod]

   public string HelloWorld()

   {

       return "Hello World";

   }

注意:将被注释的[System.Web.Script.Services.ScriptService]取消注释。

2        新建一个web窗体,添加ScriptManage组件,配置如下:

<asp:ScriptManagerID="ScriptManager1"runat="server">

          <Services>

           <asp:ServiceReference Path="~/WebService1.asmx"/>

          </Services>

</asp:ScriptManager>

则在js中调用此web服务的方式为:

WebService.HelloWorld( function sucess(res){alert(res);},

                            function failed(res){alert(res);},

                           "调用web服务");

3        使用Web方法返回单个Json对象

新建一个Student类,包含SNameSSexIAge三个属性。在WebService1.cs文件中创建如下方法:

using System.Web.Script.Services;

///<summary>

   /// 返回单个Json对象

   /// </summary>

   /// <returns></returns>

   [WebMethod]

   [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

   public Student ShowInfo()

   {

       return newStudent("zww","man",26);

}

[ScriptMethod(ResponseFormat =ResponseFormat.Json)]的作用是将Student对象序列化为Json对象,以便在页面上可使用js操作。

则在页面上使用此Web服务的方式为:

WebService.ShowInfo(function(res)

                         {

                            if(res==null)return ;

                            alert(res.SName);

                         });

注:Json对象和Json格式字符串相互转换的使用方法如下,

WebService.ShowInfo(function(res)

{

        if(res==null)return ;

         //json对象序列化为字符串

         var personStr = Sys.Serialization.JavaScriptSerializer.serialize(res);

         alert(personStr);//{"__type":"Student","SName":"zww","SSex":"man","IAge","26"}

         //将字符串反序列化为json对象

         var person = Sys.Serialization.JavaScriptSerializer.deserialize(personStr,true);

         alert(person);//[object Object]

         //WebService传递的已经为json对象,直接使用“对象名.属性名”访问

         alert(res.SName);//zww

         //var str = '{name:"zww",sex:"man",color:"yellow"}';

         //var person = eval('('+ str +')');

});

4        使用Web方法返回单个Json对象(使用list容器)

using System.Web.Script.Services;

///<summary>

   /// 返回多个json对象

   /// </summary>

   /// <returns></returns>

   [WebMethod]

   [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

   public List<Student> GetAll()

   {

       List<Student> list =new List<Student>();

       Student s1 = newStudent("tom","man", 26);

       Student s2 = newStudent("mary","woman", 22);

       list.Add(s1);

       list.Add(s2);

       return list;

}

则在页面上使用此Web服务的方式为:

//操作存放具体对象的list容器对象

         WebService.GetAll(function(res)

         {

            if(res==null){return;}

            var content = "";

            for(var i=0;i<res.length;i++)

            {

                content = content + res[i].SName + "<br/>";

            }

            document.getElementById("info").innerHTML += content;

         });

5        使用自定义序列化方式(将数据记录DataTable转换为Json对象)

实现将DataTable转换为Json对象的类如下:

using System;

using System.Collections.Generic;

using System.Collections;

using System.Data;

using System.Web.Script.Serialization;

 

///<summary>

///MyJSONs的摘要说明

///</summary>

namespace ZWW.Utility

{

 

   public classDataTableConverter : JavaScriptConverter

   {

       public overrideIEnumerable<Type> SupportedTypes

       {

           get

           {

               return newType[] { typeof(DataTable) };

           }

       }

       public overrideobject Deserialize(IDictionary<string,object> dictionary, Type type,JavaScriptSerializer serializer)

       {

           throw new NotImplementedException();

       }

       public overrideIDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer)

       {

           DataTable listType = obj as DataTable;

           if (listType != null)

           {

               // Create the representation.

               Dictionary<string,object> result = newDictionary<string,object>();

               ArrayList itemsList = new ArrayList();

               foreach (DataRow rowin listType.Rows)

               {

                   //Add each entry to the dictionary.

                   Dictionary<string,object> listDict = newDictionary<string,object>();

                   foreach (DataColumn dcin listType.Columns)

                   {

                       listDict.Add(dc.ColumnName, row[dc]);

                   }

                   itemsList.Add(listDict);

               }

               result["Rows"] = itemsList;

               return result;

           }

           return newDictionary<string,object>();

       }

   }

 

}

将此类文件存放在App_Code文件夹下,并在web.config文件中添加如下项:

 <system.web.extensions>

   <scripting>

     <webServices>

       <jsonSerializationmaxJsonLength="1024000">

         <converters>

           <addname ="DataTableConverter"type=" ZWW.Utility.DataTableConverter"/>

         </converters>

       </jsonSerialization>

     </webServices>

   </scripting>

 </system.web.extensions>

WebService1.cs中创建如下方法:

[WebMethod]

   [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

   public DataTable QueryAll()

   {

       return DB.QueryAll().Tables[0];

   }

其中DB.QueryAll()返回类型为DataSet

则在页面上调用此Web服务的方式为:

 

         //直接操作json后的DataTable

         WebService.QueryAll (function(res)

         {

            if(res==null){return;}

            var content = "";

            for(var i=0;i<res.Rows.length;i++)

            {

                content = content + res.Rows[i]["code"] +"<br/>";

            }

            document.getElementById("info").innerHTML += content;

         });

原创粉丝点击