SeouliteLab

jQuery .load() 메서드: 외부 콘텐츠 동적으로 불러오기 본문

프로그래밍

jQuery .load() 메서드: 외부 콘텐츠 동적으로 불러오기

Seoulite Lab 2024. 4. 3. 13:11

예제 1: HTML 파일 로드하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .load() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#content").load("example.html");
    });
  </script>
</head>
<body>
  <div id="content">
    <!-- 외부 HTML 파일이 여기에 로드됨 -->
  </div>
</body>
</html>

설명: 이 예제에서는 load() 메서드를 사용하여 외부의 HTML 파일인 example.html을 로드하여 현재 페이지의 #content 요소에 추가합니다.

예제 2: 외부 페이지의 일부 요소만 로드하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .load() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#content").load("example.html #specific-content");
    });
  </script>
</head>
<body>
  <div id="content">
    <!-- example.html의 #specific-content만 여기에 로드됨 -->
  </div>
</body>
</html>

설명: 이 예제에서는 load() 메서드를 사용하여 외부의 HTML 파일인 example.html에서 #specific-content라는 특정 요소만 로드하여 현재 페이지의 #content 요소에 추가합니다.

예제 3: 외부 데이터 파일 로드하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .load() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#data").load("data.txt");
    });
  </script>
</head>
<body>
  <div id="data">
    <!-- 외부 텍스트 파일의 내용이 여기에 로드됨 -->
  </div>
</body>
</html>

설명: 이 예제에서는 load() 메서드를 사용하여 외부의 텍스트 파일인 data.txt을 로드하여 현재 페이지의 #data 요소에 추가합니다.

예제 4: 로드 완료 후 콜백 함수 실행하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .load() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#content").load("example.html", function(responseTxt, statusTxt, xhr){
        if (statusTxt == "success") {
          console.log("로드 완료!");
        }
        if (statusTxt == "error") {
          console.log("에러 발생: " + xhr.status + ": " + xhr.statusText);
        }
      });
    });
  </script>
</head>
<body>
  <div id="content">
    <!-- 외부 HTML 파일이 여기에 로드됨 -->
  </div>
</body>
</html>

설명: 이 예제에서는 load() 메서드의 콜백 함수를 사용하여 로드가 성공했는지 또는 실패했는지를 확인합니다.

예제 5: URL 파라미터를 이용한 동적 데이터 로드하기

<!DOCTYPE html>
<html>
<head>
  <title>jQuery .load() 메서드 예제</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function(){
      var url = "dynamic_data.php";
      var params = { id: 123 };
      $("#dynamic-content").load(url, params);
    });
  </script>
</head>
<body>
  <div id="dynamic-content">
    <!-- 동적으로 로드될 데이터가 여기에 표시됨 -->
  </div>
</body>
</html>

설명: 이 예제에서는 URL 파라미터를 이용하여 동적 데이터를 로드합니다.