Created
October 5, 2022 01:47
-
-
Save mrgarita/c54e7daf4325f24a119009299e617081 to your computer and use it in GitHub Desktop.
JSON読み込み基本 古い方法(XMLHttpRequest)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "Alice", | |
"age": 13, | |
"sex": "female" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="main.js"></script> | |
<title>JSON形式の読み込み基本1</title> | |
</head> | |
<body> | |
<h1>XMLHttpRequestを使った例</h1> | |
<p>コンソールに表示しています...</p> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// --------------------------------------------------------------------------------- | |
// main.js : XMLHttpRequestを使って非同期にJSONファイルを読み込む | |
// --------------------------------------------------------------------------------- | |
// JSONファイルを読み込む関数 | |
function readJSON(){ | |
// JSONデータを一括してdataに読み込む | |
let data = JSON.parse(this.responseText); | |
// JSON全体 | |
console.log(data); | |
// 個別に取り出す | |
console.log("name:" + data.name); | |
console.log("age:" + data.age); | |
console.log("sex:" + data.sex); | |
} | |
window.addEventListener("load", ()=>{ | |
// HTTP通信を行う | |
const httpObj = new XMLHttpRequest(); | |
// JSONデータ読み込み後の処理 | |
httpObj.addEventListener("load", readJSON); | |
// JSONファイルを取得する(非同期通信:第3引数trueの場合) | |
httpObj.open("GET", "data.json", true); | |
// HTTPリクエストを送信する | |
httpObj.send(null); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment