JavaScript FetchAPI 给出了不确定的结果,认为我需要移动fetch_call函数,但不确定在哪里


尝试

连接到Unsplash API,但我无法弄清楚为什么它不起作用。我尝试在我的 show_data 函数中移动提取以及创建自己的 fetch_call 函数,但似乎都不起作用。有什么想法吗?

const IMAGE_URI = "API_KEY";
function show_data(json) {
  const image_data = json.results;
  const gallary = document.querySelector("#gallery div");
  let copy = "";
  for (let i = 0; i < image_data.length; i++) {
    copy += '<div class="image-container">';
    copy +=
      '<img src="' +
      image_data[i].urls.regular +
      '" alt="wallpaper" class="wallpaper"';
    copy += '<div class="overlay-content">';
    copy += '<div><img src="assets/user.svg" alt="user">';
    copy += '<p>"' + image_data[i].users.name + '"</p></div>"';
    copy += '<div><img src="assets/like-before.svg" alt="likes">';
    copy +=
      '<p>"' + image_data[i].users.total_likes + '"</p></div></div></div>"';
  }
  if (image_data == null || image_data == undefined) {
    copy += "<p>Can not Connect to Unsplash</p>";
  }
  image_data.innerHTML = copy;
}
function fetch_call() {
  fetch(IMAGE_URI)
    .then(function(response) {
      return response.json();
    })
    .then(function(json) {
      show_data(json);
    });
}
document.addEventListener("DOMContentLoaded", show_data, false);

发布的代码不会调用fetch_call 。尝试更改

document.addEventListener("DOMContentLoaded", show_data, false);

 document.addEventListener("DOMContentLoaded", fetch_call, false);

然后fetch_call可以使用实际的 JSON 结果调用show_data

因为image_data不是 DOM 元素image_data.innerHTML = copy;我要做的就是将image_data.innerHTML = copy;更改为 gallery.innerHTML = copy; 。猜猜我只是忽略了它。

最新更新