第一种 原始法
采用了Js Ajax原生的方法来实现
html代码:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
//创建Ajax对象
function CreateXmlHttp()
{
try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) { try { xmlHttp = new XMLHttpRequest(); }
catch (e) { xmlHttp = false; }}}
}
function ShowAjax(PID)
{
var url="Process.ashx?PID="+ PID +"&rd="+Math.random();
CreateXmlHttp();
AjaxProcess(url,"spFile");
}
function AjaxProcess(url,id)
{
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = AjaxSumbitemployment;
xmlHttp.send(null);
function AjaxSumbitemployment()
{
if (xmlHttp.readyState == 4){
if(xmlHttp.status==200)
{
if(xmlHttp.responseText=="success")
{
alert("成功!");
}
else
{
alert("失败!");
}
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="show1" type="button" value="显示1" onclick='ShowAjax("1");' />
<input id="show2" type="button" value="显示2" onclick='ShowAjax("2");' />
</div>
</form>
</body>
</html>
后端使用一般处理文件.ashx:
using System;
using System.Web;
public class Process: IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string PID = context.Request.QueryString["PID"];
if (!String.IsNullOrEmpty(PID))
{
if (int.Parse(PID)==1)
{
context.Response.Write("success");
}
else
{
context.Response.Write("fail");
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
第二种 实现ICallBackEventHandler接口方法
html代码:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
<script type="text/javascript">
function CallServer(product)//请求服务器
{
<%= ClientScript.GetCallbackEventReference(this, "product", "ReceiveServerData",null)%>;
}
function ReceiveServerData(rValue) //接收服务器的返回值rValue
{
alert(rValue);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button onclick="CallServer('测试')" runat="server" id="btnTest">CallServer</button>
</div>
</form>
</body>
</html>
aspx.cs:
需要要实现接口ICallbackEventHandler
private string CallBackValue = string.Empty;
/// <summary>
/// 处理并返回值到前台的ReceiveServerData
/// </summary>
/// <returns></returns>
string ICallbackEventHandler.GetCallbackResult()
{
return CallBackValue + ",ok";
}
/// <summary>
/// 获取并设置回调值
/// </summary>
/// <param name="eventArgument"></param>
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
this.CallBackValue = eventArgument;
}
或者
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClientScriptManager csManager = Page.ClientScript;
string callbackMethod = csManager.GetCallbackEventReference(this, "document.getElementById('btnTest').value", "ReceiveServerData", "this.value");
btnTest.Attributes.Add("OnClick", callbackMethod);
}
}