簡體   English   中英

將數據從API推送到數組

[英]Pushing data from an API to an Array

我無法理解如何將數據從API傳遞到數組。 我想做的是獲取一個國家的當前人口,然后將其放入數組。 哪個國家取決於輸入內容。

我在正確的軌道上嗎? 我怎樣才能做到這一點? 我嘗試了很多不同,並且這段代碼是我得到的最新代碼。

document
  .querySelector("#newListElement")
  .addEventListener("submit", function(e) {
    e.preventDefault();

    getCountry(country).then(function() {
      list.push({
        id: uuidv4(),
        text: e.target.elements.text.value
        /* How do I send along Country Population Today with this object?*/
      });

      saveListElements(list);
      renderList(list);
      e.target.elements.text.value = "";
    });
  });

function getCountry(country) {
  var url = `http://api.population.io/1.0/population/${country}/today-and-tomorrow`;

  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.responseType = "json";

    request.onload = function() {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(Error(request.statusText));
      }

      request.onerror = function() {
        reject(Error("Network Error"));
      };

      request.send();
    };
  });
}

我建議您先閱讀該頁面,然后再繼續

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

//the promise's result is the first argument of the resolve handler.
getCountry(country).then(function(myResult) { 
      list.push({
        id: uuidv4(),
        text: e.target.elements.text.value,
        result:myResult
      });

      saveListElements(list);
      renderList(list);
      e.target.elements.text.value = "";
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM