每日一库:microAjax.js

microAjax.js是08年的一个tiny ajax lib,现在看起来极简陋了。

function microAjax(url, callbackFunction){
  this.bindFunction = function (caller, object) {
    return function() {
      return caller.apply(object, [object]);
    };
  };

  this.stateChange = function (object) {
    if (this.request.readyState==4)
      this.callbackFunction(this.request.responseText);
  };

  this.getRequest = function() {
    if (window.ActiveXObject)
      return new ActiveXObject('Microsoft.XMLHTTP');
    else if (window.XMLHttpRequest)
      return new XMLHttpRequest();
    return false;
  };

  this.postBody = (arguments[2] || "");

  this.callbackFunction=callbackFunction;
  this.url=url;
  this.request = this.getRequest();
  
  if(this.request) {
    var req = this.request;
    req.onreadystatechange = this.bindFunction(this.stateChange, this);

    if (this.postBody!=="") {
      req.open("POST", url, true);
      req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      req.setRequestHeader('Connection', 'close');
    } else {
      req.open("GET", url, true);
    }

    req.send(this.postBody);
  }
}

调用:

new microAjax("http://www.cnblogs.com/zhuzf/",function (res) {
  alert(res);
});

问题:就是没有new貌似也能调用,其实这样很不可取,都注册倒了window上了,造成全局变量污染。

作者如果要搞原型的话,应该注册到prototype,这样上述的问题不会存在,而且性能也好点(不用每个实例都复制一份函数了)

posted @ 2013-01-23 13:18  zhuzefu  阅读(305)  评论(0编辑  收藏  举报