Javascript
파일 읽기 XMLHttpRequest - # .txt # .json
taltal
2023. 1. 30. 20:19
728x90
반응형
실습환경 Django
1. XMLHttpRequest를 이용해서 .json 파일과 .txt 파일을 읽기
static/sample.txt
"Hello My name is Kim"
index.html
<body>
<div id="test"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/static/sample.txt', true);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 200) {
var data = xhr.response;
document.querySelector("#test").innerText = data;
console.log(data);
}
};
xhr.send();
</script>
</body>
xhr.open('GET', 'static'sample.txt', true);에서 true는 Asynchronous 의미 (false -> Synchronous)
*. json 형태로 저장되어 있는 경우
static/sample.txt
{"a": 1, "b": 2}
index.html
<body>
<div id="a" style="background-color: pink;"></div>
<div id="b" style="background-color: yellow;"></div>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'static/sample.txt', true);
xhr.responseType = 'json';
xhr.onload = function() {
if (xhr.status === 200) {
var data = xhr.response;
console.log(data);
document.querySelector("#a").innerText = data.a;
document.querySelector("#b").innerText = data.b;
}
};
xhr.send();
</script>
</body>
.json 파일도 가능
fetch API를 이용하는 방법도 추후에 포스팅 하도록 하겠습니다.
참고사이트:
https://ko.javascript.info/xmlhttprequest
728x90
반응형