Skip to content

Instantly share code, notes, and snippets.

@shun91
Created February 18, 2018 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shun91/7bb180c6fb29d4233b11de3269d3f279 to your computer and use it in GitHub Desktop.
Save shun91/7bb180c6fb29d4233b11de3269d3f279 to your computer and use it in GitHub Desktop.
クリックイベントでAjaxによりAPIリクエストするサンプル(Chromeではクロスオリジンの制約により動きません)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>クリックイベントでAjaxによりAPIリクエストするサンプル</title>
</head>
<body>
<main>
<h1>クリックイベントでAjaxによりAPIリクエストするサンプル</h1>
<p>
<button id="button">APIをリクエストする!</button>
<pre id="result" style="border: solid;">結果がここに表示されます。</pre>
</p>
</main>
<script>
// API の エンドポイント。ここをリクエストしたいAPIに変えればOK。
const endpoint = location.href;
// id が button の HTML 要素を取得
const button = document.getElementById('button');
// button にクリックイベントを登録
button.addEventListener('click', (event) => {
// Ajax 通信を行うのに必要な XMLHttpRequest を生成
const xhr = new XMLHttpRequest();
// リクエストの設定 (以下だと GET で endpoint を非同期でリクエストする)
xhr.open('GET', endpoint, true);
// リクエスト実行後の動作
xhr.onreadystatechange = () => {
// 実行後、レスポンスが帰ってきた時は 4 になる
if (xhr.readyState === 4){
// 「結果がここに表示されます」の部分にレスポンスを表示する
const result = document.getElementById('result');
// レスポンステキストが xhr.responseText に格納されている。
result.innerHTML = xhr.responseText;
}
};
// APIリクエストを実行
xhr.send(null);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment