본문 바로가기
Development (국비 복습 )/JavaScript

[Ajax] .onload() 함수란 무엇일까?

by Puddingforever 2023. 2. 11.

 

https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_first 

 

 

W3Schools online HTML editor

The W3Schools online code editor allows you to edit code and view the result in your browser

www.w3schools.com

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    document.getElementById("demo").innerHTML =
    this.responseText;
  }
  xhttp.open("GET", "ajax_info.txt");
  xhttp.send();
}
</script>

</body>
</html>

Ajax를 만드는 기본 순서

1.button의 loadDoc() 함수가 움직이기 위한 큰 틀을 만든다.
2.XMLHttpRequest() 함수를 불러서 웹페이지 안에서 서버의 이동이 가능하게 해준다.
3.window의 onload() 함수를 쓴다.

여기서 onload()를 쓴 이유는, 컴파일링 순서에 따라 에러가 날 수도 있기 때문이다.

xttp.open("GET","ajax_info.txt");

xttp.send(); 이 먼저 실행된 후, id="demo"로 결과값으로 전달이 되야되는데 더 편리하게 보기 위해 순서를 바꿨기 떄문이다.

이러한 DOM구조를 해결하기 위해, onload()로 값을 받는다. 

 

------ 2023-02-15

 

틀렷음...

XMLHttpRequest란 것에 onload()라는 메소드가 있는 것임

브라우저가 서버로 응답을 받을 때 사용되는 메소드이며, 이벤트가 발생하면 함수가 호출된다.

 

댓글