首页 > 编程 > .NET > 正文

ASP.NET 2.0 AJAX中Webservice调用方法示例

2024-07-10 13:08:58
字体:
来源:转载
供稿:网友

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>
    <scripting>
      <webservices>
        <jsonserialization>
          <converters>
            <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="datatableconverter" type="microsoft.web.preview.script.serialization.converters.datatableconverter, microsoft.web.preview"/>
          </converters>
        </jsonserialization>
      </webservices>
    </scripting>
  </system.web.extensions>
web服务1:ws1

using system;
using system.web;
using system.collections;
using system.web.services;
using system.web.services.protocols;
using microsoft.web.script.services;
using system.data;
/**//// <summary>
/// ws1 的摘要说明
/// </summary>
[webservice(namespace = "http://tempuri.org/")]
[webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
[scriptservice]
public class ws1 : system.web.services.webservice {

    public ws1 () {

        //如果使用设计的组件,请取消注释以下行
        //initializecomponent();
    }

    [webmethod]
    public string servertime()
    {
        return string.format("now: {0}", datetime.now);
    }

    [webmethod]
    public datatable getdatatable()
    {
        datatable dt = new datatable("person");

        dt.columns.add(new datacolumn("name", typeof(string)));
        dt.columns.add(new datacolumn("lastname", typeof(string)));
        dt.columns.add(new datacolumn("email", typeof(string)));

        dt.rows.add("kui", "he", "[email protected]");
        dt.rows.add("ren", "chao", "[email protected]");

        return dt;
    }
}


web服务2:ws

using system;
using system.web;
using system.collections;
using system.web.services;
using system.web.services.protocols;
using microsoft.web.script.services;

/**//// <summary>
/// ws 的摘要说明
/// </summary>
[webservice(namespace = "http://tempuri.org/")]
[webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
[scriptservice]
public class ws : system.web.services.webservice {

    public ws () {

        //如果使用设计的组件,请取消注释以下行
        //initializecomponent();
    }

    [webmethod]
    [scriptmethod(usehttpget = true)]
    public string helloworld(string query)
    {
        string inputstring = server.htmlencode(query);
        if (!string.isnullorempty(inputstring))
        {
            return string.format("hello, {0}. ", inputstring);
        }
        else
        {
            return "query string is null or empty";
        }
    }

}


二、前台页面:
注意要点:
需要使用的后台webservice的方法均设置在如下位置

        <asp:scriptmanager id="scriptmanager1" runat="server">
            <services>
                <asp:servicereference path="~/ws.asmx" />
                <asp:servicereference path="~/ws1.asmx" />
            </services>
        </asp:scriptmanager>
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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>untitled page</title>

    <script language="javascript" type="text/javascript" src="js.js">
    </script>

</head>
<body>
    <form id="form1" runat="server">
        <asp:scriptmanager id="scriptmanager1" runat="server">
            <services>
                <asp:servicereference path="~/ws.asmx" />
                <asp:servicereference path="~/ws1.asmx" />
            </services>
        </asp:scriptmanager>
        <div>
            <asp:button id="button1" runat="server" text="button" onclientclick="dd();return false;" />
            <div id="time">
            </div>
            <div id="list1">
                <asp:dropdownlist id="ddl1" runat="server" width="187px">
                </asp:dropdownlist>
                </div>
           
        </div>
    </form>
</body>
</html>

三、javascript程序:
注意要点:
ajax november ctp 需要用 eval() 方法将其转换成一个datatable对象(并且要裁掉最前面的"("),而ajax december ctp 支持以下方法转换“sys.preview.data.datatable.parsefromjson(result)”

    function dd()
    {
        ws.helloworld(  
                         'hekui',
                         function(result)
                         {
                            alert(result);
                         }
                     );
        ws1.servertime( 
                         function(result)
                         {
                            alert(result);
                            var divtime = document.getelementbyid("time");
                            divtime.innerhtml = result;
                         }
                     );
       ws1.getdatatable(
                         function(result)
                         {
                            // 获取到下拉框控件
                            var list = document.getelementbyid("ddl1");
                                                      
                            //ajax november ctp 需要用 eval() 方法将其转换成一个datatable对象(并且要裁掉最前面的"(")
                            var text= result.dataarray.substring(0,result.dataarray.length -1);           
                            var table = eval( text);
                           
                            //ajax december ctp 支持以下方法转换
//                            var table = sys.preview.data.datatable.parsefromjson(result);
                           
                            //清除下拉框原有列表项
                            for (x=list.options.length-1; x > -1; x--)
                            {
                                list.remove(0);
                            }
                           
                            //从获取的datatable添加数据到下拉框列表项
                            for (x=0; x < table.length; x++ )
                            {
                                //获取每一行
                                var row = table[x];         
                                //创建一个列表项                 
                                var option = document.createelement("option");
                                //列表项显示文本赋值
                                option.text = row.name + " " + row.lastname;  
                                //列表项选项值赋值
                                option.value = row.email;                     

                                //判断浏览器类型,进行项目添加    
                                if ( window.navigator.appname.tolowercase().indexof("microsoft") > -1)
                                   list.add(option); 
                                else
                                   list.add(option, null);         
                            }
                         }
                       );
    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表