我无法从我的JQuery调用进入我的Search WebMethod.也许有人可以帮我指出正确的方向.
我还将所有内容打包成一个zip文件,如果有人想查看它以便仔细查看.
http://www.filedropper.com/jsonexample
谢谢瑞恩
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!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>JSON Example</title>
<script type="text/javascript" language="JavaScript" src="jquery-1.3.1.min.js"></script>
<script type="text/javascript" language="javascript">
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);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="text" id="searchbox" size="40" />
<a href="#" onclick="Search()" id="goSearch">Search</a>
<br />
<div id="Load" />
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这是default.aspx背后的代码
Imports System.Data
Imports System.Web.Services
Imports System.Web.Script.Serialization
Partial Class _Default
Inherits System.Web.UI.Page
<WebMethod()> _
Public Shared Function Search(ByVal text As String) As IEnumerable
Return "test"
End Function
End Class
Run Code Online (Sandbox Code Playgroud)
Dav*_*ard 15
要解决这样的问题,首先要做的是在Firebug中观看它.
如果单击"搜索"链接并在Firebug的控制台中观察POST请求/响应,您将看到它丢失了500服务器错误:无效的JSON原语.
原因是因为未引用"数据"JSON文字中的键/值标识符.第17行应该是:
data: "{'text':'" + search + "'}",
Run Code Online (Sandbox Code Playgroud)
然后,所有都将按预期工作.
注: 建议的数据{测试:搜索}将无法正常工作.如果您为jQuery提供实际的JSON文字而不是字符串,它会将其转换为test = search和POST的键/值对,而不是JSON.这也将导致ASP.NET AJAX ScriptService或PageMethod抛出Invalid JSON Primitive错误.
您需要执行以下操作(C#):
public static[WebMethod]属性进行修饰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
}
Run Code Online (Sandbox Code Playgroud)