📜  从 fetch api 中获取数据到变量中 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:44.340000             🧑  作者: Mango

代码示例3
function getFromAPI(url, callback){
  var obj;
  fetch(url)
    .then(res => res.json())
    .then(data => obj = data)
    .then(() => callback(obj))
 }

getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);

function getData(arrOfObjs){
  var results = "";
  arrOfObjs.forEach( (x) => {
    results += "

Id: " + x.id + "

    " Object.keys(x).forEach( (p) => { results += "
  • " + (p + ": " + x[p]) + "
  • "; }); results += "


" }) results += ""; document.getElementById("myDiv").innerHTML = results; }