ASP.NET:无法使用jQuery调用页面WebMethod
我在页面的代码隐藏文件中创建了WebMethod,如下所示:ASP.NET:无法使用jQuery调用页面WebMethod,jquery,asp.net-ajax,webmethod,Jquery,Asp.net Ajax,Webmethod,我在页面的代码隐藏文件中创建了WebMethod,如下所示: [System.Web.Services.WebMethod()] public static string Test() { return "TEST"; } 我创建了以下HTML页面来测试它: <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.
[System.Web.Services.WebMethod()]
public static string Test()
{
return "TEST";
}
我创建了以下HTML页面来测试它:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/></script>
<script type="text/javascript">
function test() {
$.ajax({
type: "POST",
url: "http://localhost/TestApp/TestPage.aspx/Test",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(msg) {
alert(msg.d);
}
});
}
</script>
</head>
<body>
<button onclick="test();">Click Me</button>
</body>
</html>
函数测试(){
$.ajax({
类型:“POST”,
url:“http://localhost/TestApp/TestPage.aspx/Test",
数据:“{}”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“文本”,
成功:功能(msg){
警报(msg.d);
}
});
}
点击我
当我单击该按钮时,AJAX启动,但没有返回任何内容。调试代码时,甚至不会调用方法
Test()
。有什么想法吗?您需要将Test()设置为接受/允许POST如果页面方法在您的页面上正确注册,您应该能够使用Microsoft注册的对象PageMethods调用它们
您的javascript应该在aspx页面加载所有特定于Microsoft的库之后运行。加载这些内容后,可以通过以下方式调用PageMethod:
Test(函数()OnSucceeded{},函数()OnFailed{})
以下是指向更好示例的链接:
如果您还没有,我强烈建议您使用Firebug来帮助调试这些客户端调用。Firebug将为您提供确定实际情况所需的所有信息
getfirebug.com试试看
url: "TestPage.aspx/Test"
或者任何会出现在页面上的相对url
您可能无意中违反了
另外,尽管您还没有到达那里,但是您希望看到一个d:wrapped对象。实际上,你只需要得到一个字符串
这会让你到达你想去的地方
function test() {
$.ajax({
type: "POST",
url: "TestPage.aspx/Test",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
}
});
}
我使用此javascript函数使用jQuery调用WebMethods:
function pageMethod(fn, params, successFn, errorFn) {
var pagePath = window.location.pathname;
var jsonData = $.toJSON(params);
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: jsonData,
dataType: "json",
success: successFn,
error: errorFn
});
}
$.toJson序列化是由jquery.json-1.3插件实现的
正如您所看到的,数据类型必须是“json”我认为数据类型应该是“json”。添加一个错误函数以查看返回的错误状态,即404未找到、500服务器错误等--服务器端只需WebMethod即可。-1欢迎使用StackOverflow。这个问题明确指出jQuery正在使用中。MsAjax不需要发布到页面方法。OK,这很公平。在我听来,他似乎在寻找一种方法让它发挥作用,而我提供了另一种选择。我同意MsAjax不需要让它工作,但它将是可用的,并且可能是一个可行的替代方案。这个问题确实明确指出jQuery正在使用,但没有说在哪里必须使用jQuery。很抱歉,Jeremy。我本应该更清楚,但是的,必须通过jQuery。如果我将来决定走MsAjax路线,我肯定会记住你的反应。我不是疯了,只是征收一些新税让你做好准备。你会掌握窍门的。作为上下文,考虑这个问题:我问如何解决我在C中遇到的问题,并且你回答“嘿,你可以在红宝石中这样做……”——我画这个平行来帮助你理解为什么我否决了你。p、 别介意,我只是个老顽皮鬼。问题解决了!感谢代码诗人和所有其他回答的人。这是双重的:数据类型是问题的一部分,所以我给了每个回答这一部分的人投票。最终,这归结为无意中违反了同一原产地政策,这就是我将此标记为解决方案的原因。再次感谢大家。谢谢你!谢谢分享!我将继续使用这个方便的小函数。