原生Ajax

原生的ajax:

  1. 创建 XMLHttpRequest 对象
    try{
    xhr = new XMLHttpRequest;
    }catch(e){
    xhr = new ActiveObject(“Microsoft.XMLHTTP”)
    }

  2. xhr.open(type,url,asyns) 规定请求数据的类型,地址,以及是否异步(false)
    type: ‘get’/’post’等
    url: 发送请求地址
    asyns: true/false(默认异步)

  3. 回调函数:
    xhr.onreadystatechange = function (){
    //当请求发送到服务器时,做一些响应
    }

    1. xhr.send(); 将请求发送发到服务器上
      1.> type = ‘get’ ; xhr.send(null);
      2.> type = ‘post”;
      xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
      xhr.send(param); //param: 要发送的数据

如: 封装了一个函数;
function myAjax(data){

//                定义对象
                var xhr = null;
//                做兼容性
                try{
                    xhr = new XMLHttpRequest();
                }catch(e){
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }
    var type = data.type == 'get' ? 'get' :'post';
       var url = data.url;
       var flag = data.asny == 'true'?'true':'false';
       xhr.open(type,url,flag);

// 发送

                if(data.type == 'get'){
//                    发送null , 是为了兼容老版的浏览器
                    xhr.send(null);
                }else if(data.type == 'post'){
                    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    xhr.send(data.data);
                }

// 回调函数

             xhr.onreadystatechange = function () {
                  if(xhr.readyState == 4){
                      if(xhr.status == 200){
                          if(typeof data.success == 'function'){
                              var d = data.dataType == 'xml' ? xhr.responseXML : xhr.responseText;
                              data.success(d);
                          }
                      }else if(typeof data.failure == 'function'){
                          data.failure();
                      }
                  }
              }
          }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值