ajax,response查看不到,真能看到console.log里面能打印出来

原因是

request.onreadystatechange = cb(request)
直接把结果赋值给了onreadystatechange,等于没有了毁掉函数,当然什么都看不到了
改进的方法是
request.onreadystatechange = function(){cb(request)};

 

var Ajax

(function(){

var request = false

function createRequest() {

  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    //两种微软的XMLHttpRequest
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }
  if (!request)
    alert("Error initializing XMLHttpRequest!");
}

createRequest();

Ajax.Get = function (url,cb){
  request.open("GET",url);
  //XHR对象的readyState有很多值,表示不同的状态,每次状态改变都会触发onreadystatechange这个函数
  //所以不能确保是发送完了以后的request
  request.onreadystatechange = function(){
    if(request.readyState==4){
      cb(request)
    }
  };
  request.send(null);
}
//一json的格式发送
Ajax.Post = function(){
  //var len = arguments.length;
  url  = arguments[0]
  cb   = arguments[1]
  form = arguments[2]
  request.open("POST",url);
  request.onreadystatechange = function(){
    if(request.readyState==4){
      request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

      cb(request);
    }
  }
  if form !=null{
    var postStr = JSON.stringify(form);
    request.send(postStr);
  }else{
    request.send();
  }
}

})();

完整方法

posted @ 2014-02-22 16:12  ggaaooppeenngg  阅读(957)  评论(0编辑  收藏  举报