我在下面设置了一个断点,WebMethod但是我从未达到过断点。
WebMethod
CS:
[WebMethod] public static string search() { return "worked"; }
aspx:
function search() { $.ajax({ type: "POST", url: "ProcessAudit/req_brws.aspx/search", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { alert(msg) } }); } <button id = "btnSearch" onclick = "search()" >Search</button>
确保在ScriptManager元素中启用了页面方法:
ScriptManager
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
并且您已经通过在onclick处理程序中返回false来取消了按钮的默认操作,否则页面将执行完整的回发,并且您的AJAX调用可能永远没有时间完成。这是一个完整的工作示例:
<%@ Page Language="C#" %> <script type="text/c#" runat="server"> [System.Web.Services.WebMethod] public static string search() { return "worked"; } </script> <!DOCTYPE html> <html> <head id="Head1" runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" /> <button id="btnSearch" onclick="search(); return false;" >Search</button> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> function search() { $.ajax({ type: 'POST', url: '<%= ResolveUrl("~/default.aspx/search") %>', data: '{ }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { alert(msg.d) } }); } </script> </body> </html>
另一种可能性是毫不客气地订阅点击处理程序:
<button id="btnSearch">Search</button>
然后在一个单独的javascript文件中:
$('#btnSearch').click(function() { $.ajax({ type: 'POST', url: '<%= ResolveUrl("~/default.aspx/search") %>', data: '{ }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { alert(msg.d) } }); return false; });
您可能还会注意到msg.dASP.NET用于将整个响应包装到的成功回调中的属性的用法,以及ResolveUrl正确生成page方法的URL而不是对其进行硬编码的方法的用法。
msg.d
ResolveUrl