使用JQuery调用WebMethod

我无法从我的JQuery调用进入我的Search WebMethod。 也许有人可以帮我指出正确的方向。

我还将所有内容打包成一个zip文件,因为有人想要仔细检查一下。

http://www.filedropper.com/jsonexample

谢谢瑞恩

    JSON Example   function Search() { var search = $("#searchbox").val(); var options = { type: "POST", url: "Default.aspx/Search", data: "{text:" + search + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { alert('Success!'); } }; $.ajax(options); }    
Search

这是default.aspx背后的代码

  Imports System.Data Imports System.Web.Services Imports System.Web.Script.Serialization Partial Class _Default Inherits System.Web.UI.Page  _ Public Shared Function Search(ByVal text As String) As IEnumerable Return "test" End Function End Class 

要解决这样的问题,首先要做的是在Firebug中观看它。

如果单击“搜索”链接并在Firebug的控制台中观察POST请求/响应,您将看到它丢失了500服务器错误:无效的JSON原语。

原因是因为未引用“数据”JSON文字中的键/值标识符。 第17行应该是:

 data: "{'text':'" + search + "'}", 

然后,所有都将按预期工作。

注意:建议的数据{test:search}不起作用。 如果您为jQuery提供实际的JSON文字而不是字符串,它会将其转换为test = search和POST的键/值对,而不是JSON。 这也将导致ASP.NET AJAX ScriptService或PageMethod抛出Invalid JSON Primitive错误。

您需要执行以下操作(C#):

  • WebMethod必须是public static
  • 它必须使用[WebMethod]属性进行修饰
  • 您需要在.aspx页面上使用ScriptManager
  • 设置ScriptManager的EnablePageMethods="true"

这里有一些示例javascript:

 $().ready(function() { $(yourDropDownList).change(LoadValues); }); function LoadValues() { PageMethods.YourMethod(arg1, CallSuccess, CallFailed); } function CallFailed(result) { alert('AJAX Error:' + result.get_message()); } function CallSuccess(result) { //do whatever you need with the result }