• Web Services And Ajax


    Web Service 与Ajax来实现一个加法运算;

    1。创建一个ASP。NET web 项目;

    2。添加一个Web Service到项目中去;

    namespace AjaxWCF
    {
        /// <summary>
        /// AjaxService 的摘要说明
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
        [System.Web.Script.Services.ScriptService]
        public class AjaxService : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string HelloWorld()
            {
                return "Hello World";
            }
    
            [WebMethod]
            public int add(int a, int b)
            {
                return a + b;
            }
        }
    }
    注意:一定要加[System.Web.Script.Services.ScriptService],并且还在自己写的方法头上加[WebMethod]

    运行Service,结果如下:

    image

    在URL加上JS,将提供JS代理文件下载:

    image

    在页面中添加ScriptManager,并引用WebService

    <asp:ScriptManager ID="ScriptManager1" runat="server">
               <Scripts>
                   <asp:ScriptReference Path="~/AjaxService.asmx/js" />
               </Scripts>
           </asp:ScriptManager>

    注意:这里也可以引用,你刚才下载的JS文件,也可以直接调用WEB service

    添加两个文本框,用来输入数据,完事代码如下:

    <form id="form1" runat="server">
       <div>
           <asp:ScriptManager ID="ScriptManager1" runat="server">
               <Scripts>
                   <asp:ScriptReference Path="~/AjaxService.asmx/js" />
               </Scripts>
           </asp:ScriptManager>
           A:<input id="txtA" type="text" /><br />
           B:<input id="txtB" type="text" /><br />
           <input id="Button1" type="button" value="OK" onclick="add()" />
       </div>
       </form>

     

    现在在Head部分添加JS代码;

    <script language="javascript" type="text/javascript">
           function add() {
               var a = $get("txtA").value;
               var b = $get("txtB").value;
    
               AjaxWCF.AjaxService.add(a, b, message);
           }
    
           function message(res)
           { alert(res); }
       </script>

    注意:AjaxWCF.AjaxService.add()方法就是JS文件中的一个代理方法,可以在JS文件中找到;

    image

    上面这个图就是JS文件的全部代码,有兴趣的朋友可以去研究一下;

    最后运行结果如下:

    image

  • 相关阅读:
    1052 Linked List Sorting (25 分)
    1051 Pop Sequence (25 分)
    1050 String Subtraction (20 分)
    1049 Counting Ones (30 分)
    1048 Find Coins (25 分)
    1047 Student List for Course (25 分)
    1046 Shortest Distance (20 分)
    1045 Favorite Color Stripe (30 分)
    1044 Shopping in Mars (25 分)
    1055 The World's Richest (25 分)
  • 原文地址:https://www.cnblogs.com/caodaiming/p/1447165.html
Copyright © 2020-2023  润新知