您的位置:首页 > 其它

Ajax使用PageMethods调用后台方法

2012-06-27 17:44 351 查看
很多东西都不会,从头学起;这里贴使用PageMethods调用后台方法

在后台上写两个方法,一个是有参,一个无参

[System.Web.Services.WebMethod]

[System.Web.Script.Services.ScriptMethod]

public static object GetStatus()

{

return System.DateTime.Now.ToString();

}

[System.Web.Services.WebMethod]

[System.Web.Script.Services.ScriptMethod]

public static object SetName(string firstName, string lastName)

{

return firstName + " " + lastName;

}

在脚本上进行调用

<script language="javascript" type="text/javascript">

/*

注意事项:

(a)需要调用的服务器端方法必须以System.Web.Services.WebMethod特性进行标记

(b)需要调用的服务器端方法必须为公共静态方法

(c)需要调用的服务器端方法应写在.aspx页面(或对应的后台代码文件)中,不应写在用户控件中

*/

window.setInterval(function () {

PageMethods.GetStatus(function (result) {

if (result) {

alert(result);//弹出当前时间

}

});

}, 3000);

window.onload = function () {

PageMethods.SetName("zhang", "jinshan", function (result) {

alert(result);//弹出姓名

});

}

//以下的写法是错误的:直接

PageMethods.SetName("zhang", "jinshan", function (result) {

alert(result);//弹出姓名

});

</script>

在表单中需要添加 EnablePageMethods="true"

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

</asp:ScriptManager>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: