본문 바로가기
프로그래밍/javascirpt

[javascript] ajax 웹 페이지 비동기 자동 갱신

by IT맥구리나스 2023. 3. 2.

개요

- 페이지 새로고침 없이 비동기 자동 갱신 방식

- AJAX는 "Asynchronous JavaScript and XML"의 약자, 사용자가 전체 페이지를 새로고침하지 않고도 웹페이지에서 동적으로 콘텐츠를 업데이트할 수 있는 기술

 

아래 코드는 test 파일내용을 읽어 들이는데, test파일 수정이 일어나면 자동으로 페이지 내용도 갱신되는 코드이다.

<div id="fileContens"> </div> 사이에 test 파일의 내용이 출력되며 1000은 1초로, 1초마다 갱신을 뜻한다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>자동 갱신 페이지</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

  <h1>자동 갱신 페이지</h1>

  <div id="fileContents"></div>

  <script>
    function refreshFileContents() {
      $.get('test', function(data) {
        $('#fileContents').text(data);
      });
    }

    setInterval(refreshFileContents, 1000);
  </script>


</body>
</html>
반응형

'프로그래밍 > javascirpt' 카테고리의 다른 글

[javascript] ajax 를 이용한 값 저장  (0) 2023.02.16

댓글