XMLHttpRequestと後継のfetch APIについて
XMLHttpRequest
XMLHttpRequestは、urlを指定してリクエストを送信することができる機能である。
基本的な使い方は以下の様になっている
const xhr = new XMLHttpRequest(); xhr.open('GET', 'http://~~~'); xhr.send(); xhr.onload = () => { console.log(xhr.response); }); xhr.onerror = () => { console.log('error'); }
open()
で対象urlを指定する。このとき、POSTとGETの2種類から選択する
send()
が実際に実行する部分
onload
は、実行が完了したあとに処理される部分
ただし、この処理のあとに、onloadした結果を使いたいとなった場合、その処理が完了するのを待たなくてはいけない
なにも考えずに使うとonloadの処理中に次にいってしまうため扱いづらい
fetch API
fetch APIは、よりシンプルに記述できるようになったもの
IEでは使えなさそう(Edgeは使えそう)
https://caniuse.com/#search=fetch
使い方は以下の様になる
fetch('http://~~~').then((response) => { console.log(response.status); }).catch(() => { console.log('error'); });
メソッドチェーンを作って記述できるので、確実に処理の流れをつかんで記述できる
メソッドチェーンを作らずに async/await
を使うことで、よりきれいに書くことができる
(async() => { try { const response = await fetch('http://~~~'); console.log(response.status); } catch (e) { console.log(e); } })();
外部から関数化して呼び出す場合は以下のようにする
const func = async() => { try { const response = await fetch('http://~~~'); console.log(response.status); } catch (e) { console.log(e); } }
async/await
を使うことで、よりスマートに書くことができる
参考文献
XMLHttpRequest
- 第12回 XMLHttpRequest入門:これでできる! クロスブラウザJavaScript入門|gihyo.jp … 技術評論社
- XMLHttpRequest の使い方 - WebOS Goodies