JavaScriptのFetch APIで非同期通信を行ってJSONを取得するサンプルです。
| 確認環境 ・Windows 10 ・Google Chrome |
目次
Fetch API
- 非同期通信でデータを取得できます。
- 戻り値は、ResponseオブジェクトのPromiseを返します 。
- 未対応のブラウザがあるので確認が必要です。IEは未対応です。
- 以下は、MDNのFetch 概説のリンクです。
https://developer.mozilla.org/ja/docs/Web/API/Fetch_API/Using_Fetch - 以下は、MDNのResponseのリンクです。
https://developer.mozilla.org/ja/docs/Web/API/Response
POSTでデータを送信してJSONを取得する
POSTでデータを送信してJSONを取得するサンプルです。
9行目のボタンを押すとPOSTで通信が始まります。
テストするサイトとしてhttpbin(http://httpbin.org/)を指定しています。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>サンプル</title>
</head>
<body >
<form id="form1">
<input type="button" value="ボタン1" onclick="clickBtn1()">
<input type="text" name="cs1" value="custom1" maxlength="7">
<input type="text" name="cs2" value="custom2" maxlength="7">
</form>
<script>
function clickBtn1(){
const form1 = new FormData(document.getElementById("form1"));
fetch("http://httpbin.org/post",{
method:"POST",
body:form1
})
.then(function(response1) {
console.log("status=" + response1.status); //例 200
return response1.json();
})
.then(function(data1) {
console.log(JSON.stringify(data1));
})
.catch(function(err1) {
console.log("err=" + err1);
});
}
</script>
</body>
</html>
16行目は、データを送信するため10,11行目のテキストボックスの名前と値を設定しています。
18行目は、fetchです。
22,26行目の.thenは、成功した時に実行されます。
23行目は、HTTPステータスコードを表示します。成功時は200です。
27行目のstringifyメソッドは、JavaScriptオブジェクトをJSONに変換しています。
29行目の.catchはエラーが発生した時に実行されます。
以下は、MDNのFormDataのリンクです。
https://developer.mozilla.org/ja/docs/Web/API/FormData
GETでデータを送信してJSONを取得する
GETでデータを送信してJSONを取得するサンプルです。
9行目のボタンを押すとGETで通信が始まります。
テストするサイトとしてhttpbin(http://httpbin.org/)を指定しています。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>サンプル</title>
</head>
<body >
<input type="button" value="ボタン1" onclick="clickBtn1()">
<input type="text" name="cs1" id="cs1" value="custom1" maxlength="7">
<input type="text" name="cs2" id="cs2" value="custom2" maxlength="7">
<script>
function clickBtn1(){
const para1 = new URLSearchParams();
para1.set("cs1",document.getElementById("cs1").value);
para1.set("cs2",document.getElementById("cs2").value);
fetch("http://httpbin.org/get?" + para1.toString())
.then(function(response1) {
console.log("status=" + response1.status); //例 200
return response1.json();
})
.then(function(data1) {
console.log(JSON.stringify(data1));
})
.catch(function(err1) {
console.log("err=" + err1);
});
}
</script>
</body>
</html>
16~18行目は、データを送信するため10,11行目のテキストボックスの名前と値を設定しています。
20行目は、fetchです。
22,26行目の.thenは、成功した時に実行されます。
23行目は、HTTPステータスコードを表示します。成功時は200です。
27行目のstringifyメソッドは、JavaScriptオブジェクトをJSONに変換しています。
29行目の.catchはエラーが発生した時に実行されます。
※methodオプションのデフォルトはGETなので、method:"GET"の記述は不要です。
以下は、MDNのURLSearchParamsのリンクです。
https://developer.mozilla.org/ja/docs/Web/API/URLSearchParams
関連の記事