笔记-Ajax[3]-ajax类终极版;

function Ajax(method,url,data,success){

    var xhr;
    //1:创建对象
    try {
      xhr = new XMLHttpRequest();
    } catch (e) {
      xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
//2:建立请求
   if(method=='get'){
      if(data){
        url += '?' + data+"&"+new Date().getTime();//解决get方式的缓存问题
      }
      xhr.open(method,url,true);
   }else{
      xhr.open(method,url,true);
      xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');//申明发送的数据类型
   }

//3:发送请求

  if(method=='get'){
    xhr.send();//当为get方式的时候这个参数为空
  }else{
    data?xhr.send(data):xhr.send();//当为post方式的时候这个参数为数据
  }

//4:回应
xhr.onreadystatechange = function() {

  if ( xhr.readyState == 4 ) {
    if ( xhr.status == 200 ) {
        success && success(xhr.responseText);//回调函数处理数据
    } else {
        alert('出错了哥们,Err:' +xhr.status);   

    }
  }
   }

};

 调用 :

Ajax('post','date.txt','',function(data){
  alert(data);
});

原文地址:https://www.cnblogs.com/hellome/p/3771085.html