Ajax XMLHttpRequest Level 2 新特性

242 阅读1分钟

相比于传统的XML,XML level 2新特性一共四个: 1、可以设置HTTP请求时限 2、可以试用FromData对象管理表单数据 3、可以上传文件 4、可以获取数据传输的进度信息

设置HTTP请求时限

<script>
  var xhr = new XMLHttpRequest();
  //设置超时时间 30毫秒会执行请求超时,3000毫秒会正常返回结果
  xhr.timeout = 30;
  xhr.timeout = 3000;
  xhr.ontimeout = function () {
    console.log('请求超时了');
  }
  xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks');
  xhr.send();
  xhr.onreadystatechange = function () {
    if(xhr.readyState=== 4 && xhr.status === 200) {
      console.log(xhr.responseText);
    }
  }
</script>

FormData对象模拟表单操作

<script>
  //创建FormData
  var fd = new FormData();
  //为FormData添加表达项
  fd.append('uname','zs');
  fd.append('upawd','123456');
  //创建xhr对象
  var xhr = new XMLHttpRequest();
  //指定请求类型与URL地址
  xhr.open('POST','http://www.liulongbin.top:3006/api/formdata');
  //直接提交FormData对象,这与提交页面表单的效果完全一样
  xhr.send(fd);

  xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
    }
  }

</script>

FormData对象获取网页form表单的值,转换成FormData对象提交

<form id="form1">
  <input type="text" name="uname" autocomplete="off">
  <input type="password" name="password" id="upwd">
  <button type="submit">提交</button>
</form>

<script>
  var form = document.querySelector('#form1');
  form.addEventListener('submit',function (e) {
    //组织表单默认行为
    e.preventDefault();

    //创建FormData,快速获取到form表单中的数据
    var fd  = new FormData(form);

    var xhr = new XMLHttpRequest();
    xhr.open('POST','http://www.liulongbin.top:3006/api/formdata');
    xhr.send(fd);

  xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && xhr.status === 200){
      //JSON对象转字符串
      console.log(JSON.parse(xhr.responseText))
    }
  }
  })
</script>

新特性 1、上传文件, 2、显示文件上传进度 以图片为例

<body>
<!--文件选择框-->
<input type="file" name="" id="file1">
<!--上传文件的按钮-->
<button id="btnUpuload">上传文件</button>
<br>
<!--显示上传成功以后的图片-->
<img src="" alt="" id="img" width="800">

<script>
  //获取文件上传的按钮
  var btnUpload = document.querySelector('#btnUpuload');
  // 为按钮添加点击事件,点击了说明要开始上传了
  btnUpload.addEventListener('click',function () {
    // 获取选的文件放入到files方法中
    var files = document.querySelector('#file1').files;
    // 如果files中的长度为零说明没有文件
    if(files.length <= 0) {
      return alert('没有文件!')
    }
  //  不为零继续后续业务
  //   创建FormData对象
    var fd = new FormData();
    // 利用FormData能够上传文件,向FormData追加文件
    fd.append('avatar',files[0]);

    // 创建xhr对象
    var xhr = new XMLHttpRequest();

    // 显示文件上传进度
    // 监听xhr.upload的onprogress事件
    xhr.upload.onprogress = function (e) {
      // e.lengthComputable是一个布尔值,表示当前上传的资源是否局有可计算的长度
      if(e.lengthComputable)
        // e.loaded已传输的字节
        // e.total需要传输的总字节
        // 当前进度除以总长度,乘以100以百分比输出,通过ceil向上取整
      var percentComplete = Math.ceil((e.loaded / e.total)*100);
       // 在控制台查看进度
      console.log(percentComplete+'%');
    }


    // 调用open函数,指定请求类型和URL地址,上传文件要用post
    xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar');
    // 发起请求
    xhr.send(fd);

    // 监听onreadystatechange事件
    xhr.onreadystatechange = function () {
      // 如果端口为4,状态码为200说明服务器响应成功
      if(xhr.readyState === 4 && xhr.status === 200) {
        // 将JS内容转成JSON对象,responseText时后台返回来的数据
        var data = JSON.parse(xhr.responseText)
        if(data.status === 200) {//上传文件成功
          // 上传成功地图片显示出来
          document.querySelector('#img').src = 'http://www.liulongbin.top:3006'+data.url;
        }else {//上传失败
          //data是对象的数据,messae是属性内容是上传结果
          console.log(data.message);
        }

      }
    }
  })

</script>
</body>