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

posted @ 2009-04-30 17:31  阳光追梦  阅读(469)  评论(1编辑  收藏  举报
/*快速评论*/ #div_digg { position: fixed; bottom: 10px; right: 15px; border: 2px solid #ECD7B1; padding: 10px; width: 140px; background-color: #fff; border-radius: 5px 5px 5px 5px !important; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); } /** 不知道为什么页面加载完成时还读不到div_digg。可能也是动态生成的。 所以这里只能用定时器 不断的读取,当读取到了再给它动态添加快捷按钮 **/ //自定义 定时器[当元素加载完成是执行回调函数] function customTimer(inpId,fn) { if ($(inpId).length) { fn(); } else { var intervalId = setInterval(function () { if ($(inpId).length) { //如果存在了 clearInterval(intervalId); // 则关闭定时器 customTimer(inpId,fn); //执行自身 } }, 100); } } //页面加载完成是执行 $(function () { customTimer("#div_digg", function () { var div_html = "
\ 关注\  | \ 顶部\  | \ 评论\
"; $("#div_digg").append(div_html); //tbCommentBody }); });