从 Stack Overflows API 显示当月的 JavaScript 问题

我们可以向 Stack Exchange 的 API 发出一个 AJAX 请求,以检索当月的顶级 JavaScript 问题列表,然后将它们显示为链接列表。如果请求失败或返回 API 错误,则我们的 promise 错误处理会显示错误。

Version >= 6

在 HyperWeb 上查看实时结果

const url =
    'http://api.stackexchange.com/2.2/questions?site=stackoverflow' +
    '&tagged=javascript&sort=month&filter=unsafe&key=gik4BOCMC7J9doavgYteRw((';

fetch(url).then(response => response.json()).then(data => {
  if (data.error_message) {
    throw new Error(data.error_message);
  }

  const list = document.createElement('ol');
  document.body.appendChild(list);

  for (const {title, link} of data.items) {
    const entry = document.createElement('li');
    const hyperlink = document.createElement('a');
    entry.appendChild(hyperlink);
    list.appendChild(entry);

    hyperlink.textContent = title;
    hyperlink.href = link;
  }
}).then(null, error => {
  const message = document.createElement('pre');
  document.body.appendChild(message);
  message.style.color = 'red';

  message.textContent = String(error);
});