使用Fetch发送Ajax请求

背景

  • 早期我们可以使用XMLHttpRequest对象来发送ajax请求,但是需要书写多行代码。
// 创建xhr对象
let xhr = new XMLHttpRequest()
// 发送get请求
xhr.open('get', 'https://api.github.com/')
// 监听状态的改变
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    // 请求成功后获取数据
    console.log(xhr.responseText)
  }
}
// 发送请求
xhr.send()
  • 后来有了jQuery,我们可以采用封装后的ajax方法或者getpost等等方法
$.ajax('https://api.github.com/', {
  success: data => {
    // 请求成功的回调函数
    console.log(data);
  },
  error: err => {
    // 请求失败的回调函数
    console.log(err);
  }
})
  • 不过现在浏览器支持FetchAPI了,可以无需其他库就能实现ajax

Fetch获取数据

语法:

fetch('url').then(response =>{
  /*do something*/
})
  • fetch方法调用返回一个Promise
  • 想要获取数据则需要调用response适当的方法将可读流转换为我们可以使用的数据。如果方法使用不当则会报错
  • 所有这些获取可以使用数据的方法(response.json等)返回另一个Promise,需要调用.then方法后处理我们转换后的数据
fetch('https://api.github.com/users/test')
	// 转换数据
  .then(response => response.json())
  // 获取响应的json数据
  .then(data => {
  	console.log(data);
	})
  .catch(err => console.log(err))

Fetch发送数据

语法:

fetch('url',options)
  • 设置请求方法(如getpost)。默认情况下为get
  • 设置头部,因为一般使用JSON数据格式,所以设置ContentTypeapplication/json
  • 设置包含JSON内容的主题。
let content = {some: 'content'};

// The actual fetch request
fetch('some-url', {
  method: 'post',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(content)
})
// .then()...

参考文档

原文地址:https://www.cnblogs.com/it774274680/p/15347727.html