客户端访问Web Service(下) <!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 runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"> </asp:ScriptManager> <input type="button" value="Get Current Time" οnclick="getCurrentTime()" /> <mce:script language="javascript" type="text/javascript"><!-- function getCurrentTime() { PageMethods.GetCurrentTime(getCurrentTimeSucceeded); } function getCurrentTimeSucceeded(result) { alert(result); } // --></mce:script> </div> </form> </body> </html> using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Web.Services; public partial class _2_PageMethods : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static DateTime GetCurrentTime() { return DateTime.UtcNow; } } 错误处理 <!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 runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="ErrorHandling.asmx" /> </Services> </asp:ScriptManager> <input type="button" value="getDivision" οnclick="getDivision(5, 0)" /> <input type="button" value="timeout" οnclick="timeout()" /> <mce:script language="javascript" type="text/javascript"><!-- function getDivision(a, b) { ErrorHandling.GetDivision(a, b, null, failedCallback); } function timeout() { ErrorHandling.set_timeout(2000); ErrorHandling.Timeout(null, failedCallback); } function failedCallback(error) { var message = String.format( "Timeout: {0}/nMessage: {1}/nExceptionType: {2}/nStackTrace: {3}", error.get_timedOut(), error.get_message(), error.get_exceptionType(), error.get_stackTrace()); alert(message); } // --></mce:script> </div> </form> </body> </html> <%@ WebService Language="C#" Class="ErrorHandling" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class ErrorHandling : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public int GetDivision(int a, int b) { return a / b; } [WebMethod] public int Timeout() { System.Threading.Thread.Sleep(5000); return 0; } }