using System.ComponentModel; using System.Web.Script.Services; using System.Web.Services; namespace AjaxCallWebServiceInWebFormDemo { /// <summary> /// WebService1 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 [ScriptService] public class WebService1 : WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } /// <summary> /// 和某人打招呼 /// </summary> /// <param name="name">名字</param> /// <returns>和某人打招呼</returns> [WebMethod(CacheDuration = 60, Description = "和某人打招呼!")] public string SayHelloToSomeone(string name) { return $"Nice to meet you, {name}."; } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="AjaxCallWebServiceInWebFormDemo.Index" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>WebForm种Ajax调用WebService</title> <script src="Scripts/jquery-3.4.1.min.js"></script> <script type="text/javascript"> $(function() { $("#btnAjaxCallWebService").click(function() { $.ajax({ type: 'POST', contentType: 'application/json', url: 'WebService1.asmx/SayHelloToSomeone', dataType: 'json', data: '{ name: "LDH" }', success: function(data) { alert('执行结果:' + data.d); console.log('%c 执行成功!', 'color:pink;font-size:50px'); }, error: function(data) { alert(data.responseText); console.log('%c 执行失败!' + data.responseText, 'color:red;font-size:50px'); }, complete: function() { alert('执行完成!'); console.log('%c 执行完成!', 'color:green;font-size:50px'); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <input type="button" id="btnAjaxCallWebService" value="Ajax调用WebService"/> <%--<button id="btnAjaxCallWebService">Ajax调用WebService</button>--%> </form> </body> </html>