目次
1. 非同期通信とは?
ウェブ開発において非同期通信とは、ウェブページをリロードすることなくサーバーにデータをリクエストまたは送信する技術を指します。これにより、ユーザーエクスペリエンスを大幅に向上させることができます。
2. AJAXとは?
AJAXはAsynchronous JavaScript And XMLの略で、ウェブページで動的にサーバーとデータを交換できる技術です。
let xhr = new XMLHttpRequest(); xhr.open("GET", 'https://api.example.com/data', true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) console.log(xhr.responseText); } xhr.send();
3. Fetch APIとは?
Fetch APIはネットワークリクエストを送り、リソースを取得するためのシンプルなインターフェースを提供するWeb標準です。AJAXよりも直感的で柔軟なAPIを提供します。
4. Fetch APIの使い方
Fetch APIを使用してリソースを取得する基本的な方法は以下のとおりです。
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
5. コード例
Fetch APIを使用してサーバーからデータを非同期にリクエストするシンプルなコード例です。
fetch('https://api.example.com/data', { method: 'GET', headers: { 'Content-Type': 'application/json', } }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch((error) => { console.error('Error:', error); });