从客户端javascript 访问asp.net后台cs中的函数(ICallbackEventHandler接口实现),并返回string结果到javascript. 格式: <%= ClientScript.GetCallbackEventReference(this,"Arg","GetCBResult","null") %> Arg:参数,传入的; GetCBResult:返回结果处理的函数; null:上下文text,具体见提示; this:传入的控件 前台主要代码:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Asp.Net实现回调</title> <script type="text/javascript" language="javascript"> function GetCBResult(result,context) { alert("返回结果了"+result); document.getElementById('r').innerHTML=result; } function InvokeCallBack(name2) { alert('开始了~'); Arg=name2; <%= ClientScript.GetCallbackEventReference(this,"Arg","GetCBResult","null") %> } </script> </head> <body> <form id="form1" runat="server"> <div> <input type="text" id="n" /> <input type="button" value="asp.net中实现回调" οnclick="InvokeCallBack(n.value)" /> <div id="r"></div> </div> </form> 后台主要代码:
</body> </html>public partial class CallBackInAspNet : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler { private string result; // public string ForInvokeCallBack; protected void Page_Load(object sender, EventArgs e) { // ForInvokeCallBack = Page.ClientScript.GetCallbackEventReference(this, "arg", "GetCallBackResult", "context"); } #region ICallbackEventHandler 成员 /**/ /* * 对ICallbackEventHandler接口进行声明,要在客户端调用服务端代码而不回发,必须声明该接口并且实现它的两个方法: * RaiseCallbackEvent()、GetCallbackResult() * RaiseCallbackEvent()的参数是从前台传过来的,根据传来的参数执行不同的代码并将结果用GetCallbackResult()返回前台 */ public string GetCallbackResult() { return result; } public void RaiseCallbackEvent(string eventArgument) { try { result= eventArgument + " 欢迎您!!! =====哈哈,成功实现了回调了!"; } catch (Exception ex) { throw new NotImplementedException(ex.Message.ToString()); } } #endregion