AJAX - 封装AJAX GET 数组join( )方法 键值对取value POST请求参数注意点

 

 

function objToStr(obj){

  obj.t = new Date().getTime();  // 给obj动态增加了一个属性
  // 这个给对象添加属性的方法, 会被直接加到键值对里??

  /*
  {
    "userName":"lnj",
    "userPwd":"123456",
    "t":"38439034204"     // 随机的时间数值
  }
  */

  var res = [];

  for(var key in obj){
    res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key])); 
    // 注意这里键值对取值的方式
    // encodeURIComponent();  把中文转码,因为URL里不能出现中文
    // URL中只能出现 字母/数字/下划线/ASCII码
  }
  return res.join("&"); // 数组的join方法要看一下!!
}

function ajax(url, obj, timeout, success, error){

  // 0. 将对象转换为字符串
  var str = objToStr(obj);  // 函数的返回值即为这个字符串str

  // 1. 创建异步对象
  var xmlHttp, timer;

  if(window.XMLHttpRequest){
    xmlHttp = new XMLHttpRequest();
  }else{
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }

  /* 2. 设置请求方式和请求地址  open(method,url,async)
  method: 请求的类型  GET 或 POST
  url: 文件在服务器上的位置
  async: true(异步)  false(同步)
  */
  xmlHttp.open("GET", url+"?"+str, true);

  // 3. 发送请求
  xmlHttp.send();

  // 4. 监听状态的变化
  xmlHttp.onreadystatechange = function(ev2){
    /*
    0: 请求未初始化
    1: 服务器连接已建立
    2: 请求已接收
    3: 请求处理中
    4:请求已完成,且相应已就绪
    */
    if(xmlHttp.readyState === 4){
      //判断是否请求成功
      clearInterval(timer);  // 这里有点疑问,readyState状态为4,即清除定时器?

      if(xmlHttp.status >= 200 && xmlHttp.status < 300 || xmlHttp.status === 304){
        // 5. 处理返回的结果
        success(xmlHttp);
      }else{
        error(xmlHttp);
      }
    }
  }
  // 判断外界是否传入了超时时间
  if(timeout){
    timer = setInterval(() => {
      xmlHttp.abort();  // abort();  中止XMLHttpRequest对象的请求
      clearInterval(timer);
    }, timeout);
  }
}

 

  <script src="myAjax.js"></script>
  <script>
  window.onload = function(ev){
    var oBtn = document.querySelector('button');
    //var res = encodeURIComponent('张三');

    oBtn.onclick = function(ev1){

      ajax('04-ajax-get.php', {
        "userName":"lnj",
        "userPwd":"123456"
      }, 3000, // 设置服务器响应超时时间,到时间还没返回结果,就中止这次请求
      function(xhr){
        alert(xhr.responseText);
        
      }, function(xhr){
        alert('请求失败');
      })
    }
  }
  </script>

 

xhr.open("POST", "04-ajax-get.php", true); 
      // POST 的 URL后面 不能直接拼接参数, 只能通过以下方式:
      
      // 注意点:以下代码必须放到open和send之间
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

      xhr.send("userName=zs&userPwd=123");  // POST请求的参数

 

转载于:https://www.cnblogs.com/carpenterzoe/p/10387818.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值