首页 > 其他分享 >js原生xhr请求XMLHttpRequest

js原生xhr请求XMLHttpRequest

时间:2023-01-06 17:01:46浏览次数:39  
标签:function console log js xhr var XMLHttpRequest event

创建一个请求实例,发送请求

var xhr = new XMLHttpRequest();
xhr.open('GET', 'test.php');
xhr.send();

监控XMLHttpRequest对象的状态变化

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

 请求时限

xhr.timeout = 3000;
xhr.ontimeout = function(event){
  alert('请求超时!');
}

FormData对象

var formData = new FormData();
formData.append('aa', '12');
xhr.open('POST', url);
xhr.send(formData);

接收二进制数据

xhr.responseType = 'blob';
var blob = new Blob([xhr.response]);

进度信息

xhr.onprogress = function updateProgress(event) {
    if (event.lengthComputable) {
      var percentComplete = event.loaded / event.total;
    }
}

 其它回调

  xhr.onloadstart = function () {
    console.log("传输开始", 1);
  };
  xhr.onload = function () {
    console.log("传输完成", 2);
  };
  xhr.onloadend = function () {
    console.log("传输结束", 3);
  };
  xhr.onabort = function () {
    console.log("用户取消");
  };
  xhr.onerror = function () {
    console.log("error");
  };

 获取响应头信息

#获取指定响应头
xhr.getResponseHeader("content-disposition")

#获取所有响应头,字符串格式
var headers = xhr.getAllResponseHeaders().toLowerCase();

 

标签:function,console,log,js,xhr,var,XMLHttpRequest,event
From: https://www.cnblogs.com/caroline2016/p/17030986.html

相关文章

  • js content-type
    letxhr=newXMLHttpRequest()xhr.open('POST','http://xx.aa.cn/home/moban/ssds11')xhr.setRequestHeader('Content-Type','application/json')xhr.send(......
  • js 计算元素的行高与字体大小,单位px
    constgetTagFontSize=(tag:string):number=>{constele=document.createElement(tag);document.body.append(ele);const{fontSize}=getComputedStyl......
  • 第一节:环境准备、项目结构详解、App.vue/main.js/uni.scss详解、各种引用(组件/js/css
    一. 环境准备1. HbuilderX 下载地址:https://www.dcloud.io/hbuilderx.html 2. 微信开发工具 下载地址:https://developers.weixin.qq.com/miniprogram/dev......
  • 原生js常用操作
    元素#创建一个元素document.createElement("a")#附加到父元素的最后pararentEle.appendChild(childEle);#查找document.getElementById("aa")document.querySel......
  • js 数组的splice
    splice():删除、插入和替换1、删除:指定2个参数:要删除的第一项的位置和要删除的项数。书写格式:arr.splice(0,2)2、插入:可以向指定位置插入任意数量的项,只需提供3......
  • 使用ExcelJS处理Excel
    官方中文文档在浏览器环境下,用Excel.js读取excel文件使用ExcelJS的原因因为SheetJS读取样式的那一部分是收费的(具体原因是因为有人花钱找他们开发的,再免费对花钱的人......
  • JS精粹--匿名函数与自执行匿名函数
    1.函数也是一种类型要理解匿名函数,首先需要理解函数也是一种类型。所以函数可以赋值给变量,如下://将数字类型值赋给变量varnum=1;//将......
  • three.js场景地形导出到物理引擎
    太长不看版遍历场景地形里的Mesh,从geometry里抽取index和position,通过这两个数组构建物理引擎里的Trimesh。 背景最近在试制网页MMORPG,内核用最顺手的three.js,资产使......
  • 更改json节点key
    json节点key更改,给朋友写的小tool,顺便记录一下/***需要转义的key对象*原key:新key*/constjsonKeysTo={'a':'new_a','b':'new_b','c>0......
  • 解决react typescript项目中引入js库项目打包报错问题
    描述在reacttypescript项目中,在打包的过程中会报错抛出couldnotfindadeclarationfileformodule的错误,报错内容如图所示原因JS库无法在TS中正常的加载,需要修改......