我正在创建一个简单的 Web 方法来从 Java 脚本访问。但我无法
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(
function test() {
var x = PageMethods.MyMethod();
alert(x.toString());
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
</asp:ScriptManager>
</div>
</form>
</body>
</html>
后面的代码看起来像这样
[WebMethod]
public static string MyMethod()
{
return "Hello";
}
变量 x 为空。我无法弄清楚我缺少什么?有什么帮助吗?提前致谢
最佳答案
您需要定义一个回调函数,该函数在收到 Web 方法的响应时调用:
$(document).ready(
function test() {
PageMethods.MyMethod(myMethodCallBackSuccess, myMethodCallBackFailed);
})
function myMethodCallBackSuccess(response) {
alert(response);
}
function myMethodCallBackFailed(error) {
alert(error.get_message());
}
您还可以将参数传递给该方法,但是这些参数必须始终出现在成功和失败回调之前。
注意:您不需要包含失败的回调,但如果需要,可以使用它。
关于c# - 无法从 Javascript 访问 webmethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6931999/