在ASP.NET中使用Callback实现AJAX

来源:互联网 发布:话剧是什么知乎 编辑:程序博客网 时间:2024/06/05 15:03

 在许多时候,我们需要从客户端运行服务器代码而不执行回发,要实现这样的效果有非常多的方法,可以使用ASP.NET 中的 AJAX 功能,也可以使用象AjaxPro这样的第三方控件。这里我们要讨论的是使用Callback来实现AJAX。

    要实现客户端回调的ASP.NET页的CS代码与创建ASP.NET页的过程类似,但也存在一些区别。该页的服务器代码必须:1、实现ICallbackEventHandler接口;2、提供RaiseCallbackEvent方法的实现;3、提供GetCallbackResult方法的实现。同时在客户端必须三个脚本函数:1、一个函数调用帮助器方法,该方法执行对服务器的实际请求;2、客户端回调函数,处理回调事件的服务器代码的结果调用并接收该结果;3、第三个函数是执行实际服务器请求的 Helper 函数。当在服务器代码中使用 GetCallbackEventReference方法生成对此函数的引用时,ASP.NET 将自动生成此函数。

    现在,我们从实例来分析Callback的实现方法。

.aspx页源代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallbackDemo.aspx.cs" Inherits="CallbackDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>CallbackDemo</title>

    
<script type="text/javascript">
        function GetServerDateTime(context)
{
            
<%= ClientScript.GetCallbackEventReference(this, "", "ReceiveServerData", "")%>;
        }


        function ReceiveServerData(rValue)
{
            document.getElementById(
"ResultsSpan").innerHTML = rValue;

        }

    
</script>

</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<input id="btnSubmit" type="button" value="现在时间是" onclick="GetServerDateTime(ResultsSpan)" />
        
<br />
        
<span id="ResultsSpan" runat="server"></span>
    
</div>
    
</form>
</body>
</html>
 

 .aspx.cs源代码:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CallbackDemo : System.Web.UI.Page,ICallbackEventHandler
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

    
public void RaiseCallbackEvent(String eventArgument)
    
{
        
    }

    
public String GetCallbackResult()
    
{
        
return DateTime.Now.ToString();
    }


}
 

    演示中客户端注册的脚本函数:<%= ClientScript.GetCallbackEventReference(this, "", "ReceiveServerData", "")%>;。这句动态生成一个客户端函数,该函数包含对来自GetCallbackEventReference方法的返回值的调用。ClientScriptManager.GetCallbackEventReference方法有4个重载函数,上面这个方法中,"this"是处理客户端回调的服务器控件,它必须实现ICallbackEventHandler 接口并提供RaiseCallbackEvent 方法,它的类型是System.Web.UI.Control。第二个参数是从客户端脚本传递给服务器的一个参数,它是String类型的。第三个函数是客户端事件处理程序的名称,它接收成功的服务器事件的结果,这里把回调结果返回给JS中的ReceiveServerData()方法。最后一个参数是启动回调之前在客户端计算的客户端脚本。脚本的结果传回客户端事件处理程序。

    JS方法:

function ReceiveServerData(rValue) {
    document.getElementById(
"ResultsSpan").innerHTML = rValue;
}
 

 

接收服务器事件的结果,并将结果呈现出来。

    而服务器端的RaiseCallbackEvent()方法没有内容,因为这里是最简单的演示,我们没有回调参数,如果有回调参数在这个方法中处理。GetCallbackResult()则是返回当前的系统时间。

    在VS中测试刚才的DEMO,发现会在浏览器源代码中自动生成一段这样的代码:

<script src="/Callback/WebResource.axd?d=EsUKgUC2lEyf3iKipjXhYw2&amp;t=633655516704843750" type="text/javascript"></script>
 

 

这个DEMO产生的WebResource.axd有21KB大小,测试了一下,所有的文件都是一样的体积。它是在这个文件中创建了AJAX请求:

function WebForm_DoCallback(eventTarget, eventArgument, eventCallback, context, errorCallback, useAsync) {
    
var postData = __theFormPostData +
                
"__CALLBACKID=" + WebForm_EncodeCallback(eventTarget) +
                
"&__CALLBACKPARAM=" + WebForm_EncodeCallback(eventArgument);
    
if (theForm["__EVENTVALIDATION"]) {
        postData
+= "&__EVENTVALIDATION=" + WebForm_EncodeCallback(theForm["__EVENTVALIDATION"].value);
    }

    
var xmlRequest,e;
    
try {
        xmlRequest
= new XMLHttpRequest();
    }

    
catch(e) {
        
try {
            xmlRequest
= new ActiveXObject("Microsoft.XMLHTTP");
        }

        
catch(e) {
        }

    }

    
var setRequestHeaderMethodExists = true;
    
try {
        setRequestHeaderMethodExists
= (xmlRequest && xmlRequest.setRequestHeader);
    }

    
catch(e) {}
    
var callback = new Object();
    callback.eventCallback
= eventCallback;
    callback.context
= context;
    callback.errorCallback
= errorCallback;
    callback.async
= useAsync;
    
var callbackIndex = WebForm_FillFirstAvailableSlot(__pendingCallbacks, callback);
    
if (!useAsync) {
        
if (__synchronousCallBackIndex != -1) {
            __pendingCallbacks[__synchronousCallBackIndex]
= null;
        }

        __synchronousCallBackIndex
= callbackIndex;
    }

    
if (setRequestHeaderMethodExists) {
        xmlRequest.onreadystatechange
= WebForm_CallbackComplete;
        callback.xmlRequest
= xmlRequest;
        xmlRequest.open(
"POST", theForm.action, true);
        xmlRequest.setRequestHeader(
"Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        xmlRequest.send(postData);
        
return;
    }

    callback.xmlRequest
= new Object();
    
var callbackFrameID = "__CALLBACKFRAME" + callbackIndex;
    
var xmlRequestFrame = document.frames[callbackFrameID];
    
if (!xmlRequestFrame) {
        xmlRequestFrame
= document.createElement("IFRAME");
        xmlRequestFrame.width
= "1";
        xmlRequestFrame.height
= "1";
        xmlRequestFrame.frameBorder
= "0";
        xmlRequestFrame.id
= callbackFrameID;
        xmlRequestFrame.name
= callbackFrameID;
        xmlRequestFrame.style.position
= "absolute";
        xmlRequestFrame.style.top
= "-100px"
        xmlRequestFrame.style.left
= "-100px";
        
try {
            
if (callBackFrameUrl) {
                xmlRequestFrame.src
= callBackFrameUrl;
            }

        }

        
catch(e) {}
        document.body.appendChild(xmlRequestFrame);
    }

    
var interval = window.setInterval(function() {
        xmlRequestFrame
= document.frames[callbackFrameID];
        
if (xmlRequestFrame && xmlRequestFrame.document) {
            window.clearInterval(interval);
            xmlRequestFrame.document.write(
"");
            xmlRequestFrame.document.close();
            xmlRequestFrame.document.write(
'<html><body><form method="post"><input type="hidden" name="__CALLBACKLOADSCRIPT" value="t"></form></body></html>');
            xmlRequestFrame.document.close();
            xmlRequestFrame.document.forms[
0].action = theForm.action;
            
var count = __theFormPostCollection.length;
            
var element;
            
for (var i = 0; i < count; i++) {
                element
= __theFormPostCollection[i];
                
if (element) {
                    
var fieldElement = xmlRequestFrame.document.createElement("INPUT");
                    fieldElement.type
= "hidden";
                    fieldElement.name
= element.name;
                    fieldElement.value
= element.value;
                    xmlRequestFrame.document.forms[
0].appendChild(fieldElement);
                }

            }

            
var callbackIdFieldElement = xmlRequestFrame.document.createElement("INPUT");
            callbackIdFieldElement.type
= "hidden";
            callbackIdFieldElement.name
= "__CALLBACKID";
            callbackIdFieldElement.value
= eventTarget;
            xmlRequestFrame.document.forms[
0].appendChild(callbackIdFieldElement);
            
var callbackParamFieldElement = xmlRequestFrame.document.createElement("INPUT");
            callbackParamFieldElement.type
= "hidden";
            callbackParamFieldElement.name
= "__CALLBACKPARAM";
            callbackParamFieldElement.value
= eventArgument;
            xmlRequestFrame.document.forms[
0].appendChild(callbackParamFieldElement);
            
if (theForm["__EVENTVALIDATION"]) {
                
var callbackValidationFieldElement = xmlRequestFrame.document.createElement("INPUT");
                callbackValidationFieldElement.type
= "hidden";
                callbackValidationFieldElement.name
= "__EVENTVALIDATION";
                callbackValidationFieldElement.value
= theForm["__EVENTVALIDATION"].value;
                xmlRequestFrame.document.forms[
0].appendChild(callbackValidationFieldElement);
            }

            
var callbackIndexFieldElement = xmlRequestFrame.document.createElement("INPUT");
            callbackIndexFieldElement.type
= "hidden";
            callbackIndexFieldElement.name
= "__CALLBACKINDEX";
            callbackIndexFieldElement.value
= callbackIndex;
            xmlRequestFrame.document.forms[
0].appendChild(callbackIndexFieldElement);
            xmlRequestFrame.document.forms[
0].submit();
        }

    }
, 10);
}
 
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 从淘宝物流寄东西到国外被扣怎么办 不是天猫的淘宝卖家不发货怎么办 微店违规说卖假冒商品怎么办 云集微店的商品没货了怎么办 淘宝买家被检测有虚拟交易怎么办 媒体声音突然没有声音了该怎么办 华为微信运动步数为零怎么办 淘宝店铺没货了客户拍了怎么办 房子涨价了卖家反悔不卖了怎么办 买的东西很贵质量不好怎么办 在淘宝开的店账号忘了怎么办 建了个淘宝优惠券群没人购物怎么办 刚开的淘宝店没有生意怎么办 房产代理公司不给渠道结佣金怎么办 天猫超过72小时不发货怎么办 流量魔盒苹果下载怎么打不开怎么办 淘宝包邮店铺新疆地区拍怎么办 淘宝客服当顾客要优惠时怎么办 微信手机号注册的找不到了怎么办 之前注册的微信找不到了怎么办 苹果ipad的id密码忘了怎么办 淘宝和支付宝用一张银行卡怎么办 淘宝卖家填写虚假物流信息怎么办 淘宝店铺的浏览量越来越少怎么办 网上充手机话费充错了怎么办 夜神模拟器上陌陌的位置不对怎么办 如果在大庭广众之下放了个屁怎么办 淘宝分销上传宝贝被系统下架怎么办 酷狗喜欢歌单里面的歌都没了怎么办 苹果手机下载不了微信缓冲怎么办 登陆微信提示版本过低登不了怎么办 苹果手机微信版本过低登不上怎么办 微信小程序显示微信版本过低怎么办 三星手机登微信显示版本过低怎么办 微信版本低无法登录无法升级怎么办 手机淘宝五应用界面无法打开怎么办 入住淘宝主播没有微博粉丝怎么办 手机淘宝领金币怎么没有了怎么办 淘宝荬家缺货对付款买家怎么办 淘宝买家确认收货后申请退款怎么办 淘宝东西失效了但付过款了怎么办