출처 : https://www.w3schools.com 사이트의 내용을 공부하며 정리하고 있다.

AJAX는 서버와 데이터를 교환하고 전체 페이지의 재로딩 없이 웹 페이지의 부분을 업데이트 할 수 있다.


AJAX란? Asynchronous JavaScript and XML의 약자.

Gmail, Google Maps, Youtube, Facebook 등이 사용하고 있다. 


jQuery는 AJAX 기능을 위한 여러 메소드를 제공한다.

jQuery팀은 단 한줄의 코드로 AJAX 기능을 사용할 수 있도록 한다.


jQuery load( ) 메소드

-> jQuery load( ) 메소드는 단순하지만 강력한 AJAX 메소드이다.

서버로부터 데이터를 로드하고 리턴된 데이터를 선택된 요소에 넣는다. 


문법 : $(selector).load(URL,data,callback); 


아래는 demo_test.txt 라는 파일의 내용을 <div> 요소에 넣는 예제이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".div1").load("demo_test.txt");
    });
});
 
</script>
</head>
<body>
 
<div class="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
 
<button>Get External Content</button>
 
</body>
</html>
 
cs


파라미터를 콜백함수 형태로 사용할 수 있다 .이 경우 load 메소드가 완전히 끝난 뒤에 실행된다.

콜백함수는 다른 파라미터들을 가지고 있다. 


1. responseTxt : 만약 콜이 성공하면 결과 내용을 담는다.

2. statusTxt : 콜의 상태를 담는다.

3. xhr : XMLHttpRequest 객체를 담는다.



아래 예제를 통해 알아보자. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
 
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").load("demo_test.txt"function(responseTxt, statusTxt, xhr){
            if(statusTxt == "success") {
                alert("load success!!");
            } else {
                alert("fail!!! : " + xhr.status + " : " + xhr.statusText);
            }
        });
    });
});
 
</script>
</head>
<body>
 
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
 
<button>Get External Content</button>
 
</body>
</html>
 
cs

결과 : load가 완전히 끝나면 alert 창이 뜨고 이후에 효과가 나타난다.

11번 라인에 xhr.status 와 xhr.statusText를 입력하면 200, success 가 출력된다. 

+ Recent posts