1.Default.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ScriptWebSerivce" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title></title> <script type="text/javascript"> function ShowResult(res) { alert(res);} </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="MyWebService.asmx" /> </Services> </asp:ScriptManager> <script type="text/javascript"> Ajax.MyWebService.GetTotal(5, 4, ShowResult, null, "abc"); </script> </div> </form> </body> </html> |
2.MyWebService.asmx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Script.Services; namespace Ajax { /// <summary> /// MyWebService 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //[System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [ScriptService] public class MyWebService : System.Web.Services.WebService { public MyWebService() { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public int GetTotal(int x, int y) { return x + y; } } } |
注意:此方法只适合在同一个域下调用。