美文网首页
XMLHttpRequest

XMLHttpRequest

作者: 陈大事_code | 来源:发表于2019-06-04 11:13 被阅读0次
  1. 简单的数据请求
    场景: 请求一张图片,并显示在网页上。
var xhr = new XMLHttpRequest();         // 实例化一个xhr对象
xhr.open('GET', '/images/photo.webp');  // 规定请求方式和url
xhr.responseType = 'blob';              // 规定请求返回类型
xhr.onload = function() {               // 规定xhr请求完成的事件
  if (this.status == 200) {
    var img = document.createElement('img');
    img.src = window.URL.createObjectURL(this.response);
    img.onload = function() {
        window.URL.revokeObjectURL(this.src);
    }
    document.body.appendChild(img);
  }
};
 
xhr.send(); // 发送请求
  1. 数据上传
    场景:post请求上传数据。
var formData = new FormData();
formData.append('id', 123456);
formData.append('topic', 'performance');
 
var xhr = new XMLHttpRequest();
 
xhr.open('POST', '/upload');
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // 自定义请求头
xhr.onload = function() { ... };
xhr.send(formData);

其中,

  • 提交表单基本就是用FormData类型,进行上传数据。

  • xhr.send(formData),当我们想在请求接口的时候上传数据时,采用这种方式,大多为post请求。若为get请求,则不需要带参数。

相关文章

网友评论

      本文标题:XMLHttpRequest

      本文链接:https://www.haomeiwen.com/subject/wfrlxctx.html