关于AJAX类库实现模式的探索

本文介绍了一个简单的自定义AJAX库实现方案,包括服务器端和客户端组件的设计思路及核心代码示例。通过ScriptManager管理客户端脚本加载,并利用AjaxHandler处理服务器请求,实现了页面与服务器之间的异步交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先AJAX的应用是建立在 服务器端 和 客户端 的交互基础之上的,这个交互的过程通过异步的方式来实现就
达到了我们现在说看到AJAX应用的效果。 因此我们要开发一个AJAX类库的话,需要大概2个模块,服务器端类库和控件,客户端脚本库。下面给我的一个AJAX库的主要源码:

ScriptManager :
public class ScriptManager : WebControl, INamingContainer
    {
        protected void BuildControl()
        {
            base.Controls.Clear();

            AddJS("AjaxServer.Resource.AjaxClient.js");//输出客户端JS脚本库


            foreach (ServiceItem service in _services)
            {
                base.Controls.Add(service);
            }
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            ClearChildViewState();

            BuildControl();
        }
}


AjaxHandler:
public class AjaxHandler
    {

        public static void Handler(Page obj)
        {


            if (obj.Request["RegisterProxy"] == null)
            {
                AjaxInvoker.InvokeMethod(obj);
                return;
            }

            AjaxRegister.RegistePage(obj);
           

        }
              

    }

 

AjaxRegister:
public class AjaxRegister
    {

        public static void RegistePage(Page obj)
        {}//通过发射的方法得到当前Page的可用的AJAXMETHOD
      //GetCustomAttributes(typeof(AjaxMethodAttribute), true)该方法可以过滤自定义AJAXMETHOD
      //AjaxMethodAttribute需要你自己定义

}

AjaxInvoker:
 public class AjaxInvoker
    {
        public static void InvokeMethod(Page obj)
        {}//得到当前请求的Request["MethodName"],Request["MethodParameters"]
          //并通过反射的方法实现对方法的调用的到返回值,用JSONParser(自己实现)解析后返回
         //客户端。


    }

--------------------------------------------------------------------------------------------------------------------------------

客户端JS脚本库,可以使用PRORTOTYPE.js,自己在扩展以下,如:

var AjaxClient = {
    userCallBack : null,

    Invoke : function(url,method,params,options)
    {
             
      options.postBody = "MethodName="+method+"&MethodParameters="+toJSON(params);
      options.method = "post";
      
      this.userCallBack = options.onSuccess;
      options.onSuccess = this.callback.bind(this);//setup context
      
        
      
         var myAjax = new Ajax.Request(url,options)
    },

    callback : function (response)
    {
       
        var result;
        try
        {
            eval("result = "+response.responseText);
           
        }catch(e){alert("JSON Parse Error: /n"+e.message+"/n"+response.responseText);return;}
    
        if(result.Result)
                this.userCallBack(result.Data);    
            else
                alert("调用失败: /n"+result.Data);
               
                 
       
       
    }
};
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值