본문 바로가기

jQuery

[jQuery] jQuery Ajax의 기초

반응형
■ jQuery Ajax의 기초

 코드1

<html>
<head>
<title>Document</title>
    <script type="text/JavaScript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script>
        $(document).ready(function() {

        });
    </script>
</head>
<body>
</body>
</html>



 jQuery는 Ajax와 관련된 다양한 종류의 메서드를 제공한다. 이번 절에서는 가장 기본적인 jQuery의 Ajax 관련 메서드인 $.ajax( ) 메소드를 배워봅시다. $.ajax( ) 메서드를 다음 두 가지 형태로 사용할 수 있다.


 01. $.ajax(options);

 02. $.ajax(url, options);


 간단하게 $.ajax( ) 메드를 사용해 Ajax를 수행한다. $.ajax( ) 메서드의 첫 번째 매개 변수에 문자열 /Home/MuFirstStringAction을 넣고 두 번째 매개 변수에는 옵션 객체를 넣어준다.



 코드2 : $ajax( ) 메서드

<html>
<head>
<title>Document</title>
    <script type="text/JavaScript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script>
        $(document).ready(function() {
           
            $.ajax('MyFirstStringAction.txt', {
               
                success: function() { }
            });
        });
    </script>
</head>
<body>
</body>
</html>


 코드2에서 입력한 success 속성은 이벤트 이다. $.ajax( ) 메서드는 Ajax가 성공햇을 때 자동으로 success 이벤트를 실행한다. success 이벤트 핸들러의 첫 번째 매개 변수는 Ajax가 성공했을 때 받은 데이터이다. 이 데이터를 문서 객체에 추가해 본다.




 코드3 : $ajax( ) 메서드

<html>
<head>
<title>jQuery Ajax Basic</title>
    <script type="text/JavaScript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script>
        $(document).ready(function() {

            $.ajax('MyFirstStringAction.txt', {

                success: function(data) {

                    $('body').append(data);
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>
 출력결과



 프로젝트를 실행하면 위와같이 Ajax를 통해 문자열을 가져오고 출력하는 모습을 볼 수 있다. 참고로 $.ajax( ) 내부에서 XMLHttpRequest 객체를 만들어 Ajax를 수행한다. 하지만 직접 XMLHttpRequest 객체를 만드는 것보다 간단하다.


 $.ajax( ) 메서드의 매개 변수 url은 코드4처럼 옵션 속성으로 지정할 수 있다.



 코드4 : url 옵션 속성을 사용한 $.ajax( ) 메서드

<html>
<head>
<title>jQuery Ajax Basic</title>
    <script type="text/JavaScript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script>
        $(document).ready(function() {

            $.ajax({
                url : 'MyFirstStringAction.txt',
                success: function(data) {

                    $('body').append(data);
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>
 출력결과


 $.ajax( ) 메서드 옵션 객체으 ㅣ속성은 대부분 자동으로 지정되므로 아래 표 이외의 속성은 별로 신경 쓰지 않아도 된다.



 jQuery.Ajax( ) 메서드의 옵션

 옵션 속성 이름

 설명

 자료형

 async

 동기, 비동기를 지정한다.

 Boolean

 complete(jqXHR, textStatus)

 Ajax 완료 이벤트 핸들러를 지정한다.

 Function

 data

 요청 매개 변수를 지정한다.

 Object, String

 error(jqXHR, textStatus, errorThrown)

 Ajax 실패 이벤트 핸들러를 지정한다.

 Function

 jsonp
 JSONP 매개 변수 이름을 지정한다.
 String

 jsonpCallback

 JSONP 콜백 함수 이름을 지정한다.

 String, Function
 success(data, textStatus, jqXHR)

 Ajax 성공 이벤트 핸들러를 지정한다.

 Function, Array

 timeout

 만료 시간을 지정한다.
 Number
 type

 'GET' 또는 'POST'를 지정한다.

 String
 url

 대상 URL을 지정하낟.

 String


 이제, 요청 매개 변수와 함께 Ajax 요청을 수행해 본다. 코드1의 옵션 속성 중 data 속성을 사용하면 요청 매개변수를 쉽게 지정할 수 있다. 코드5처럼 $.ajax( ) 메서드의 옵션 객체에 url 속성을 입력하고 data 속성에 객체를 입력한다.



 코드5 : data 옵션 속성을 사용한 $.ajax( ) 메서드

<html>
<head>
<title>jQuery Ajax Basic</title>
    <script type="text/JavaScript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script>
        $(document).ready(function() {

            $.ajax({
                url : 'ActionWithData.php',
                data : { name : 'Wicked_MISO', age : 21 },
                success: function(data) {

                    $('body').append(data);
                }
            });
        });
    </script>
</head>
<body>
</body>
</html>

 ActionWithData.php

<h1>
<?php echo $_REQUEST["name"];?> : <?php echo $_REQUEST["age"];?>
</h1>
 출력결과


 이렇게 하면 http://localhost/jquery/ActionWithData.php?name=Wicked_MISO&age=28로 Ajax 요청을 수행한다.


 이 절에서 배운 $.ajax( ) 메서드는 수많은 속성을 직접 지정해 다양한 형태로 사용할 수 있다. 실무에서 가장 많이 사용하는 jQuery Ajax 관련 메서드가 바로 $.ajax( )이다.

반응형