XMLHttpRequestとFetch APIを使いこなす
JavaScriptで非同期通信の応答を返す方法
非同期通信とは?
そこで登場したのが非同期通信です。非同期通信は、ユーザーがアクションを起こしてもページ全体を再読み込みすることなく、必要なデータのみをサーバーと通信で取得・更新する技術です。これにより、ユーザー操作のレスポンス向上やページ読み込み時間の短縮を実現できます。
JavaScriptで非同期通信を行う代表的な方法は、以下の2つです。
- XMLHttpRequest (XHR): 従来からある非同期通信の標準的な方法です。
- Fetch API: より新しい非同期通信のAPIです。 XMLHttpRequestよりも簡潔で扱いやすいのが特徴です。
応答の返し方
非同期通信でサーバーから取得したデータは、コールバック関数を使用して処理します。コールバック関数は、通信が完了したタイミングで実行され、サーバーからの応答データを受け取ることができます。
XMLHttpRequestの場合
// サーバーにリクエストを送信
const xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
xhr.send();
// 通信完了時の処理
xhr.onload = function() {
if (xhr.status === 200) {
// 成功時の処理
const response = JSON.parse(xhr.responseText);
console.log(response);
} else {
// 失敗時の処理
console.log('通信に失敗しました');
}
};
Fetch APIの場合
// サーバーにリクエストを送信
fetch('url')
.then(response => {
if (response.ok) {
// 成功時の処理
return response.json();
} else {
// 失敗時の処理
throw new Error('通信に失敗しました');
}
})
.then(data => {
// JSONデータの処理
console.log(data);
})
.catch(error => {
// エラー処理
console.log(error);
});
非同期通信は、ユーザー操作性とページ読み込み速度を向上させる重要な技術です。JavaScriptで非同期通信を行うには、XMLHttpRequestまたはFetch APIを使用し、コールバック関数でサーバーからの応答を処理します。
サンプル1: ユーザー入力を受け取ってサーバーに送信し、結果を表示する
HTML
<input type="text" id="name" />
<button id="submit">送信</button>
<div id="result"></div>
JavaScript
const nameInput = document.getElementById('name');
const submitButton = document.getElementById('submit');
const resultElement = document.getElementById('result');
submitButton.addEventListener('click', () => {
const name = nameInput.value;
// サーバーにリクエストを送信
fetch('url', {
method: 'POST',
body: JSON.stringify({ name }),
})
.then(response => {
if (response.ok) {
// 成功時の処理
return response.json();
} else {
// 失敗時の処理
throw new Error('通信に失敗しました');
}
})
.then(data => {
// サーバーから返却された挨拶文を表示
resultElement.textContent = data.greeting;
})
.catch(error => {
// エラー処理
console.log(error);
});
});
サンプル2: サーバーからデータを取得してリストに表示する
このサンプルコードでは、サーバーから取得した商品データを表示するリストを作成します。
<ul id="products"></ul>
const productsList = document.getElementById('products');
// サーバーにリクエストを送信
fetch('url')
.then(response => {
if (response.ok) {
// 成功時の処理
return response.json();
} else {
// 失敗時の処理
throw new Error('通信に失敗しました');
}
})
.then(data => {
// サーバーから取得した商品データでリストを作成
data.products.forEach(product => {
const listItem = document.createElement('li');
listItem.textContent = product.name;
productsList.appendChild(listItem);
});
})
.catch(error => {
// エラー処理
console.log(error);
});
非同期通信の応答を返す方法:その他の方法
jQueryの使用
例:
$.ajax({
url: 'url',
method: 'GET',
success: function(response) {
// 成功時の処理
console.log(response);
},
error: function(error) {
// 失敗時の処理
console.log(error);
}
});
Axiosは、非同期通信用のライブラリです。Fetch APIよりも簡潔で、Promiseベースで記述できます。
axios.get('url')
.then(response => {
// 成功時の処理
console.log(response.data);
})
.catch(error => {
// 失敗時の処理
console.log(error);
});
Promiseは、非同期処理を扱いやすくするためのオブジェクトです。
const promise = fetch('url');
promise.then(response => {
if (response.ok) {
// 成功時の処理
return response.json();
} else {
// 失敗時の処理
throw new Error('通信に失敗しました');
}
})
.then(data => {
// サーバーから返却されたデータの処理
console.log(data);
})
.catch(error => {
// エラー処理
console.log(error);
});
非同期通信の応答を返す方法は、いくつかあります。それぞれの特徴を理解して、状況に応じて使い分けてください。
javascript ajax asynchronous