Fetch API

来源:互联网 发布:mac os官方下载地址 编辑:程序博客网 时间:2024/05/29 18:02

参考文章:fetch API和传统ajax接口的差别

机制:

  • fetchAPI支持stream读取
  • fetchAPI可以控制Header、Response(需要把Response.json().then()来调用)、Request
  • FetchAPI更支持异步Promise调用,而不是使用异步的CB调用
  • 相对起XHR,你可以用更简便的使用方式就可以发起异步请求。比起$,fetch的优势在于这是原生的。

使用方法差别:

XHR:

var xhr = new XMLHttpRequest();xhr.open('GET', url);xhr.responseType = 'json';xhr.onload = function() {  console.log(xhr.response);};xhr.onerror = function() {  console.log("Oops, error");};xhr.send();

jQuery

$.ajax(url).done(function(data)=>{console.log(data)});

FetchAPI:

fetch(url).then(function(response) {  return response.json();}).then(function(data) {  console.log(data);}).catch(function(e) {  console.log("Oops, error");});

response返回的是Response对象,可以查询到URL,也可以使用流、json等方式去调用

response.json()返回promise对象,.then方法后,即可返回服务器的responseData

response的其他方法还有:

  1. arrayBuffer()
  2. blob()
  3. json()
  4. text()
  5. formData()

FetchAPI With ES6(语法糖)

fetch(url).then(response => response.json())  .then(data => console.log(data))  .catch(e => console.log("Oops, error", e))

其他:

当然,你可以封装掉response.json这一层,使得fetch和jQuery.ajax一样使用。

0 0