Skip to content

Instantly share code, notes, and snippets.

@mrgarita
Created October 5, 2022 01:52
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 mrgarita/a74d7c4b580e78a770be2b10ae2f2337 to your computer and use it in GitHub Desktop.
Save mrgarita/a74d7c4b580e78a770be2b10ae2f2337 to your computer and use it in GitHub Desktop.
JSON読み込み基本 新しい方法を更に簡潔に記述(fetch)
{
"name": "Alice",
"age": 13,
"sex": "female"
}
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script src="main.js"></script>
<title>JSON形式の読み込み基本3</title>
</head>
<body>
<h1>fetchを使った例</h1>
<p>コンソールに表示しています...</p>
</body>
</html>
/*
* main.js : fetchを使って非同期にJSONファイルを読み込む
*/
const url = "data.json"; // 読み込むJSONファイル
// 非同期通信でJSONファイルからデータを取得
fetch(url)
.then(response => response.json())
.then(data => {
// JSON全体
console.log(data);
// 個別に取り出す
console.log("name:" + data.name);
console.log("age:" + data.age);
console.log("sex:" + data.sex);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment