事例一:
页面:
<body>
<form id="form1" runat="server">
<div>
<input id="txtMessage" value="Client:" />
<input onclick="callToServer();" type="button" value="Call to Server" />
Result :
<input id="txtResult" />
</div>
</form>
</body>
JS:
<script type="text/javascript">
function callToServer()
{
var param = document.getElementById("txtMessage").value+"dddd";
//var context = "Client Context";
<% = CallbackScript %>
//alert(this.callToServer);
}
function handleResultFromServer(result)
{
document.getElementById("txtResult").value = result;
}
</script>
后台代码:
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
private string sResult = "";
protected void Page_Load(object sender, EventArgs e)
{
}
public String CallbackScript
{
get
{
return this.ClientScript.GetCallbackEventReference(this, "param", "handleResultFromServer", null);
}
}
public void RaiseCallbackEvent(String eventArgument)
{
this.sResult = "客户端在[" + DateTime.Now.ToString() + "]传送来 [" + eventArgument + "].";
}
public string GetCallbackResult()
{
return this.sResult;
}
}
事例二:
页面+JS:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
//由button调用
function CallServer(inputcontrol, context)
{
context.innerHTML = "Loading";
arg = inputcontrol.value;
//注册回调方法
<%= ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context")%>;
}
//在回调方法中注册的接收返回结果的函数
function ReceiveServerData(result, context)
{
context.innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="提交到Label1" onclick="CallServer(TextBox1, Label1)" /><br />
<asp:Label ID="Label1" runat="server" Text="Label1:"></asp:Label>
</div>
</form>
</body>
</html>
后台代码:
public partial class Default2 : System.Web.UI.Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
}
private string str;
public void RaiseCallbackEvent(string eventArgument)
{
//可以根据传递的参数不同,调用不同的处理逻辑
str = "从服务器端返回的内容:" + eventArgument;
}
public string GetCallbackResult()
{
return str;
}
}