ASP.NET 2.0 AJAX中Webservice调用方法示例
ASP.NET 2.0 AJAX中能够在客户端js中很方便地调用服务器Webservice,以下为一些调用的示例。笔者安装的ASP.NET 2.0 AJAX
版本为AJAX November CTP。
三个示例分别为:
1 带参数的WS方法
2 不带参数的WS方法
3 参数类型为DataTable的WS方法
一、WebMethod
注意要点:
1 WebMethod类需要添加命名空间 Microsoft.Web.Script.Services,此空间需要引用Microsoft.Web.Preview.dll
2 类声明加入标签 [ScriptService]
3 在Asp.net 2.0里可以直接用DataTable作为返回类型了,但是需要在Web.config文件添加序列化转换器的属性。DataSet、DataTable、DataRow均有转换器
 <system.web.extensions>
  <system.web.extensions> <scripting>
    <scripting> <webServices>
      <webServices> <jsonSerialization>
        <jsonSerialization> <converters>
          <converters> <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview"/>
            <add name="DataSetConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, Microsoft.Web.Preview"/> <add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview"/>
            <add name="DataRowConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, Microsoft.Web.Preview"/> <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview"/>
            <add name="DataTableConverter" type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, Microsoft.Web.Preview"/> </converters>
          </converters> </jsonSerialization>
        </jsonSerialization> </webServices>
      </webServices> </scripting>
    </scripting> </system.web.extensions>
  </system.web.extensions>WEB服务1:WS1
 using System;
using System; using System.Web;
using System.Web; using System.Collections;
using System.Collections; using System.Web.Services;
using System.Web.Services; using System.Web.Services.Protocols;
using System.Web.Services.Protocols; using Microsoft.Web.Script.Services;
using Microsoft.Web.Script.Services; using System.Data;
using System.Data; /// <summary>
/// <summary> /// WS1 的摘要说明
/// WS1 的摘要说明 /// </summary>
/// </summary> [WebService(Namespace = "http://tempuri.org/")]
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService]
[ScriptService] public class WS1 : System.Web.Services.WebService {
public class WS1 : System.Web.Services.WebService {
 public WS1 () {
    public WS1 () {
 //如果使用设计的组件,请取消注释以下行
        //如果使用设计的组件,请取消注释以下行  //InitializeComponent();
        //InitializeComponent();  }
    }
 [WebMethod]
    [WebMethod] public string ServerTime()
    public string ServerTime() {
    { return String.Format("now: {0}", DateTime.Now);
        return String.Format("now: {0}", DateTime.Now); }
    }
 [WebMethod]
    [WebMethod] public DataTable GetDataTable()
    public DataTable GetDataTable() {
    { DataTable dt = new DataTable("Person");
        DataTable dt = new DataTable("Person");
 dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("Name", typeof(string))); dt.Columns.Add(new DataColumn("LastName", typeof(string)));
        dt.Columns.Add(new DataColumn("LastName", typeof(string))); dt.Columns.Add(new DataColumn("Email", typeof(string)));
        dt.Columns.Add(new DataColumn("Email", typeof(string)));
 dt.Rows.Add("kui", "he", "hekui168@163.com");
        dt.Rows.Add("kui", "he", "hekui168@163.com"); dt.Rows.Add("ren", "chao", "chaoren888@163.com");
        dt.Rows.Add("ren", "chao", "chaoren888@163.com");
 return dt;
        return dt; }
    } }
}

WEB服务2:WS
 using System;
using System; using System.Web;
using System.Web; using System.Collections;
using System.Collections; using System.Web.Services;
using System.Web.Services; using System.Web.Services.Protocols;
using System.Web.Services.Protocols; using Microsoft.Web.Script.Services;
using Microsoft.Web.Script.Services;
 /// <summary>
/// <summary> /// WS 的摘要说明
/// WS 的摘要说明 /// </summary>
/// </summary> [WebService(Namespace = "http://tempuri.org/")]
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService]
[ScriptService] public class WS : System.Web.Services.WebService {
public class WS : System.Web.Services.WebService {
 public WS () {
    public WS () {
 //如果使用设计的组件,请取消注释以下行
        //如果使用设计的组件,请取消注释以下行  //InitializeComponent();
        //InitializeComponent();  }
    }
 [WebMethod]
    [WebMethod] [ScriptMethod(UseHttpGet = true)]
    [ScriptMethod(UseHttpGet = true)] public string HelloWorld(String query)
    public string HelloWorld(String query) {
    { string inputString = Server.HtmlEncode(query);
        string inputString = Server.HtmlEncode(query); if (!String.IsNullOrEmpty(inputString))
        if (!String.IsNullOrEmpty(inputString)) {
        { return String.Format("hello, {0}. ", inputString);
            return String.Format("hello, {0}. ", inputString); }
        } else
        else {
        { return "query string is null or empty";
            return "query string is null or empty"; }
        } }
    }
 }
}

二、前台页面:
注意要点:
需要使用的后台WebService的方法均设置在如下位置
 <asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services>
            <Services> <asp:ServiceReference Path="~/WS.asmx" />
                <asp:ServiceReference Path="~/WS.asmx" /> <asp:ServiceReference Path="~/WS1.asmx" />
                <asp:ServiceReference Path="~/WS1.asmx" /> </Services>
            </Services> </asp:ScriptManager>
        </asp:ScriptManager>Default页面:
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">
<head runat="server"> <title>Untitled Page</title>
    <title>Untitled Page</title>
 <script language="javascript" type="text/javascript" src="js.js">
    <script language="javascript" type="text/javascript" src="js.js"> </script>
    </script>
 </head>
</head> <body>
<body> <form id="form1" runat="server">
    <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services>
            <Services> <asp:ServiceReference Path="~/WS.asmx" />
                <asp:ServiceReference Path="~/WS.asmx" /> <asp:ServiceReference Path="~/WS1.asmx" />
                <asp:ServiceReference Path="~/WS1.asmx" /> </Services>
            </Services> </asp:ScriptManager>
        </asp:ScriptManager> <div>
        <div> <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="dd();return false;" />
            <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="dd();return false;" /> <div id="time">
            <div id="time"> </div>
            </div> <div id="List1">
            <div id="List1"> <asp:DropDownList ID="ddl1" runat="server" Width="187px">
                <asp:DropDownList ID="ddl1" runat="server" Width="187px"> </asp:DropDownList>
                </asp:DropDownList> </div>
                </div> 
             </div>
        </div> </form>
    </form> </body>
</body> </html>
</html>
三、JavaScript程序:
注意要点:
AJAX November CTP 需要用 eval() 方法将其转换成一个DataTable对象(并且要裁掉最前面的"("),而AJAX December CTP 支持以下方法转换“Sys.Preview.Data.DataTable.parseFromJson(result)”
 function dd()
    function dd() {
    { WS.HelloWorld(
        WS.HelloWorld(    'hekui',
                         'hekui',  function(result)
                         function(result)  {
                         {  alert(result);
                            alert(result);  }
                         }  );
                     ); WS1.ServerTime(
        WS1.ServerTime(   function(result)
                         function(result)  {
                         {  alert(result);
                            alert(result);  var divTime = document.getElementById("time");
                            var divTime = document.getElementById("time"); divTime.innerHTML = result;
                            divTime.innerHTML = result; }
                         }  );
                     ); WS1.GetDataTable(
       WS1.GetDataTable( function(result)
                         function(result)  {
                         { // 获取到下拉框控件
                            // 获取到下拉框控件 var List = document.getElementById("ddl1");
                            var List = document.getElementById("ddl1");  
                                                        //AJAX November CTP 需要用 eval() 方法将其转换成一个DataTable对象(并且要裁掉最前面的"(")
                            //AJAX November CTP 需要用 eval() 方法将其转换成一个DataTable对象(并且要裁掉最前面的"(") var Text= result.dataArray.substring(0,result.dataArray.length -1);
                            var Text= result.dataArray.substring(0,result.dataArray.length -1);             var Table = eval( Text);
                            var Table = eval( Text); 
                             //AJAX December CTP 支持以下方法转换
                            //AJAX December CTP 支持以下方法转换 //                            var Table = Sys.Preview.Data.DataTable.parseFromJson(result);
//                            var Table = Sys.Preview.Data.DataTable.parseFromJson(result); 
                             //清除下拉框原有列表项
                            //清除下拉框原有列表项 for (x=List.options.length-1; x > -1; x--)
                            for (x=List.options.length-1; x > -1; x--)  {
                            { List.remove(0);
                                List.remove(0); }
                            } 
                             //从获取的DataTable添加数据到下拉框列表项
                            //从获取的DataTable添加数据到下拉框列表项 for (x=0; x < Table.length; x++ )
                            for (x=0; x < Table.length; x++ ) {
                            { //获取每一行
                                //获取每一行 var Row = Table[x];
                                var Row = Table[x];           //创建一个列表项
                                //创建一个列表项                   var option = document.createElement("option");
                                var option = document.createElement("option");  //列表项显示文本赋值
                                //列表项显示文本赋值 option.text = Row.Name + " " + Row.LastName;
                                option.text = Row.Name + " " + Row.LastName;    //列表项选项值赋值
                                //列表项选项值赋值 option.value = Row.Email;
                                option.value = Row.Email;                      
 //判断浏览器类型,进行项目添加
                                //判断浏览器类型,进行项目添加      if ( window.navigator.appName.toLowerCase().indexOf("microsoft") > -1)
                                if ( window.navigator.appName.toLowerCase().indexOf("microsoft") > -1)  List.add(option);
                                   List.add(option);   else
                                else List.add(option, null);
                                   List.add(option, null);           }
                            } }
                         } );
                       ); }
    } 
                     
                    
                 
                    
                
 


 
     
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号