Web前端之路让前端飞

如何使用Fetch API

2017-03-17  本文已影响1778人  码农氵
alt textalt text

传统的Request

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onreadystatechange = function() {
  if (this.readyState === 4) {
    if (this.status >= 200 && this.status < 400) {
      // Success!
      var resp = this.responseText;
    } else {
      // Error :(
    }
  }
};

request.send();
request = null;

jQuery ajax

$.ajax({
  type: 'GET',
  url: '/my/url',
  success: function(resp) {

  },
  error: function() {

  }
});

传统的XMLHttpRequest请求闲的非常的杂乱,而优雅的ajax又不得不额外加载jQuery这个80K左右的框架

但是现在,我们可以使用Fetch,提供了对 Request 和 Response (以及其他与网络请求有关的)对象的通用定义,它还提供了一种定义,将 CORS 和 HTTP 原生的头信息结合起来,取代了原来那种分离的定义。

But,Fetch 兼容性,可以看到,兼容性很差,移动端全军覆没,不过可以使用Fetch polyfill

alt textalt text

使用方法

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
    // Your code for handling the data you get from the API
})
.catch(function() {
    // This is where you run code if the server returns any errors
});

so easy

现在使用Fetch创建一个简单的Get请求,将从Random User API获取的数据展示在网页上

<h1>Authors</h1>
<ul id="authors"></ul>
const ul=document.getElementById('authors');
const url="https://randomuser.me/api/?results=10";

fetch(url)
.then(function(data){
})
.catch(function(err){
});

首先获取authors,定义常量URL,然后调用Fetch API并且使用上面定义的常量URL
,但是此处获取的并不是JSON,而是需要进行转换,这些方法包括:

此处我们需要返回的是json对象,所以上面的js应该:

fetch(url)
.then((resp) => resp.json()) //转换成json对象
.then(function(data) {
    dom操作
  })
})

接下来定义两个函数:

function createNode(el){
  return document.createElement(el);
}

function append(parent,el){
  retrun parent.appendChild(el);
}

编写请求成功后操作

fetch(url)
.then((resp)=>resp.json())
.then(function(data){
  let authors=data.results;
  return authors.map(function(author){
    let li=createNode('li'),
        img=createNode('img'),
        span=createNode('span');
    img.src=author.picture.medium;
    span.innerHTML=`${author.name.first} ${author.name.last}`;
    append(li,img);
    append(li,span);
    append(ul,li);
  })
})
.catch(function(err){
  console.log(err)
})

处理更多请求(POST)

Fetch默认是GET方式,此外还可以使用自定义头部与请求方式,如:

const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
    name: 'Sara'
}
// The parameters we are gonna pass to the fetch function
let fetchData = { 
    method: 'POST', 
    body: data,
    headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
    // Handle response you get from the server
});

还可以使用request构建请求对象,如:

const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
    name: 'Sara'
}
// Create our request constructor with all the parameters we need
var request = new Request(url, {
    method: 'POST', 
    body: data, 
    headers: new Headers()
});

fetch(request)
.then(function() {
    // Handle response we get from the API
})
上一篇 下一篇

猜你喜欢

热点阅读