#47·Blog

fetch 如何请求数据

作者: ljianshu创建于 2018年12月20日更新于 2022年9月19日
  1. Fetch request local text data There is a test.txt file locally, and the following code can be used to get the data in it and display it on the page.
document.getElementById('button1').addEventListener('click',getText);
function getText(){
  fetch("test.txt")
      .then((res) => res.text())//note: this is res.text()
      .then(data => {
        console.log(data);
        document.getElementById('output').innerHTML = data;
      })
      .catch(err => console.log(err));
}
  1. Fetch request local JSON data There is a posts.json file locally, and the data is obtained by using forEach to iterate through it, and then displayed on the page.
document.getElementById('button2').addEventListener('click',getJson);
function getJson(){
  fetch("posts.json")
      .then((res) => res.json())
      .then(data => {
        console.log(data);
        let output = '';
        data.forEach((post) => {
          output += `<li>${post.title}</li>`;
        })
        document.getElementById('output').innerHTML = output;
      })
      .catch(err => console.log(err));
}
  1. Fetch request network interface Get the data from https://api.GitHub.com/users, and the method is similar to that of getting local JSON data. After obtaining the data, it is also processed.
document.getElementById('button3').addEventListener('click',getExternal);
function getExternal(){
  // https://api.GitHub.com/users
  fetch("https://api.GitHub.com/users")
      .then((res) => res.json())
…