如何使用JavaScript连接到API-多个GET请求

时间:2019-06-13 05:43:36

标签: javascript xmlhttprequest

我目前正在研究以下教程“如何将API与Jav​​aScript连接”,该教程非常有用。

https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/

我设法使示例正常工作,但是很好奇我如何打开第二个GET请求。我假设我可以创建一个新的XMLHttpRequest并复制request.onload,但是有更好的方法吗?

我目前已将请求设置为从https://ghibliapi.herokuapp.com/films获取数据

我正在寻找另一个XMLHttpRequest来添加来自https://ghibliapi.herokuapp.com/species的GET数据

这是已设置的代码

// Create a request variable and assign a new XMLHttpRequest object to it
   let request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
   request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

   request.onload = function() {
   // Begin accessing JSON data here
   let data = JSON.parse(this.response)

   // If server response pull in film titles
   if (request.status >= 200 && request.status < 400) {

     data.forEach(film => {

       // Create a div with a card class
       let card = document.createElement('div')
       card.setAttribute('class','card')

       // Create a H1 and set the text content to the films title
       let h1 = document.createElement('h1')
       h1.textContent = film.title

       // Create p and set the text content to the films description
       let p = document.createElement('p')
       p.textContent = film.description

       // More data
       let director = document.createElement('p')
       director.textContent = film.director

       // Append the cards to the container element
       let container = document.querySelector('.container')
       container.appendChild(card)
       card.appendChild(h1)
       card.appendChild(p)
       card.appendChild(director)
   })

  } else {
     let errorMessage = document.createElement('div')
     errorMessage.textContent = "Gah, it's not working!"
     let app = document.querySelector('#root')
     app.appendChild(errorMessage)
  }

 }

// Send request
request.send()

0 个答案:

没有答案