從 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);
});