文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>自写一个较通用的Ajax处理类

自写一个较通用的Ajax处理类

时间:2007-04-28  来源:lagvin

  出于工作和学习的需要,参考《Ajax in Action》一书,自写了一个较通用的Ajax处理类:AjaxObject。通过创建一个AjaxObject实例,调用其方法:

sendRequest();

就可以实现对服务器的异步请求和响应,而且不受全局变量的限制。

其代码如下:

/*
 * define a javascript class, this is its constructor.
 * For using this class object, make sure define an outer Ajax Component(may be an object) "ajaxComponent",
 * which must has two methods: handleMessage(req) and handleError(req),
 * for responsing handling successful message and error message.
 */
 AjaxObject = function(ajaxComponent, url, method){

  this.ajaxComponent = ajaxComponent;
  this.url = url;
  this.method = method ? method : "POST"; //default use "post" method

 }


 AjaxObject.prototype = {
  
  sendRequest: function() {
  
   var req = this.initReqInstance();
   if(req){
    var oThis = this; //must declare a local reference to 'this' for closure

    req.onreadystatechange = function(){ //appoint callback function

     oThis.handleResponse(req);
    };
    
    try {
           req.open(this.method, this.url, true);
           req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         } catch (e) {
           alert(e);
         }
         req.send(null);
   }
  }, //!Notice: shound be separated by ','

  
  initReqInstance: function(req){
   
   var req;
   if(window.XMLHttpRequest) { // Non-IE browsers

    req = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // IE browsers

    try {
     req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (err) {
     req = new ActiveXObject("Microsoft.XMLHTTP");
    }
   }
   
   return req;
  }, //!Notice: shound be separated by ','

  
  handleResponse: function(req){
   
   if (req.readyState == 4) { // Complete

         if (req.status == 200) { // OK response

           this.ajaxComponent.handleMessage(req);
         } else { // Error handling

           this.ajaxComponent.handleError(req);
         }
      }
  } //the last key:value pair should not have ','

 };

测试函数如下:

/*test function*/
 function test()
 {
  //new a ajax helper object for ajax component

  var ajaxComponent = new Object();
  ajaxComponent.handleMessage = function(req){ //here can't use prototype way because ajaxComponent has been a "new" object.

   alert("req is OK: " + req.status);
  };
  
  ajaxComponent.handleError = function(req){
   alert("Problem: " + req.statusText);
  };

  var url = "test.do?cmd=testAjax";
  var ao = new AjaxObject(ajaxComponent, url);
  ao.sendRequest();
 }

注意:

1、要使用AjaxObject类,必须在外部定义一个“组件”,该组件可以是一个DOM对象,也可以一个普通的Ojbect对象,但这个组件必须包含两个函数:

  handleMessage(req)和handleError(req),分别处理ajax成功返回后的响应和失败返回后的响应。

2、AjaxObject的构造函数的只有前两个参数(ajaxComponent和url)是必须的,第三个(method)是可选的。

3、使用测试函数时,要将url变量的值置换成具体环境真实的值。

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载