zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    浅谈Tarjan算法及思想
    浅谈前向星
    线段树初步
    树状数组的简单运用
    字典树(trie树)的指针简单实现pascal
    排序专辑
    POJ 2155 Matrix (矩形)
    区间动态规划
    hdu-2795 Billboard---线段树
    hdu-1754 I Hate It---线段树模板题
  • 原文地址:https://www.cnblogs.com/caodaiming/p/1447165.html
Copyright © 2011-2022 走看看