通過ScriptManager在用戶端來調用伺服器端方法或者webService的方法

來源:互聯網
上載者:User
好久沒有來寫東西了,最近工作比較忙,除了正常的工作需求要處理外還要準備一些文檔,ppt和Demo,因為這次的Ajax Training我也花了不少時間去準備。昨天終於培訓完了,好像手裡一下需求處理一樣的輕鬆了,回顧一下最近的工作遇到的問題也不是很多,今天就把幾個用戶端調用伺服器端的方法拿出來吧:
1。用戶端調用伺服器端方法:源檔案中的代碼
 1 <script language=javascript type="text/javascript">
 2    function GetCurrentTime()
 3    {
 4        PageMethods.GetCurrentTime('NewEgg ajax training',CheckIsSuccess);
 5    }
 6    function CheckIsSuccess(result)
 7    {
 8        alert(result);
 9    }
10    </script>
11
12    <input id="Button1" type="button" value="用戶端控制項調用伺服器端的方法" onclick="GetCurrentTime()" />伺服器端的方法
1[WebMethod]
2        public static string GetCurrentTime(string str)
3        {
4            return str + DateTime.Now.ToLongTimeString();
5        }

這樣就可以了,然後還一個地方要設定的就是ScriptManager有個屬性:EnablePageMethods="true"
2。用戶端調用WebService的方法:原始碼:
 1 <asp:ScriptManager ID="ScriptManager1" runat="server">
 2            <Services>
 3                <asp:ServiceReference Path="AjaxTestWebService.asmx" InlineScript="true" />
 4            </Services>
 5        </asp:ScriptManager>
 6        <br />
 7        這個就是用用戶端的方法去調用WebService裡面的方法&nbsp;<div>
 8        <input id="Button1" type="button" value="點擊調用WebService裡邊的方法產生一個隨機數" onclick="getRandom()" />
 9
10        <script language="javascript" type="text/javascript">
11            function getRandom()
12            {
13                Ajax_Dear.AjaxTestWebService.GetRandom(getR);
14            }
15            function getR(result)
16            {
17                alert(result);
18            }
19        </script>WebService的方法
 1 [WebService(Namespace = "http://tempuri.org/")]
 2    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 3    [ScriptService]
 4    public class AjaxTestWebService : System.Web.Services.WebService
 5    {
 6
 7        [WebMethod]
 8        public string HelloWorld()
 9        {
10            return "Hello World";
11        }
12        [WebMethod]
13        public int GetRandom()
14        {
15            return new Random(DateTime.Now.Millisecond).Next();
16        }
17    }

這個就沒有什麼好說的啦,代碼說明一切問題,

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.