我在下面的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元素中启用了页面方法:
<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',success: function (msg) { alert(msg.d) } }); return false; });
您可能还会注意到成功回调中msg.d属性的使用,ASP.NET使用它来包装整个响应,以及使用ResolveUrl方法正确生成页面方法的URL而不是硬编码。