jQuery를 이용해서 Ajax를 사용하면 많은 이점이 있는데 그 중의 하나가 브라우저들 간의 차이점을 jQuery가 알아서 해결해준다는 것이다. 뿐만 아니라 jQuery는 여러가지 편리한 기능들을 제공한다. jQuery를 이용해서 Ajax 통신을 하는 법을 알아보자.

 

jQuery는 Ajax와 관련해서 많은 API를 제공한다.

http://api.jquery.com/category/ajax/

 

Ajax | jQuery API Documentation

Register a handler to be called when Ajax requests complete. This is an AjaxEvent. Register a handler to be called when Ajax requests complete. This is an AjaxEvent. Register a handler to be called when Ajax requests complete with an error. This is an Ajax

api.jquery.com

그 중에서 가장 중요한 API는 $.ajax이다.

 


$.ajax

http://api.jquery.com/jQuery.ajax/

 

jQuery.ajax() | jQuery API Documentation

Description: Perform an asynchronous HTTP (Ajax) request. The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available

api.jquery.com

 

$.ajax의 문법
jQuery.ajax( [settings] )

setting은 Ajax 통신을 위한 옵션을 담고 있는 객체가 들어간다. 주요한 옵션은 다음과 같다.

  • data
    서버로 데이터를 전송할 때 이 옵션을 사용한다.
  • dataType
    서버측에서 전송한 데이터를 어떤 형식의 데이터로 해석할 것인가 지정한다. 값으로 올 수 있는 것은 xml, json, script, html이다. 형식을 지정하지 않으면 jQuery가 알아서 판단한다.
  • success
    성공했을 때 호출할 콜백을 지정한다.
    Function(PlainObject data, String textStatus, jqXHR jqXHR)
  • type
    데이터를 전송하는 방법을 지정한다. get, post를 사용할 수 있다.

POST 방식

[time2.php]

1
2
3
4
5
<?php
$d1 = new DateTime;
$d1->setTimezone(new DateTimezone($_POST['timezone']));
echo $d1->format($_POST['format']);
?>
cs

 

[demo2.html]

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
<p>time : <span id="time"></span></p>
<form>
    <select name="timezone">
        <option value="Asia/Seoul">asia/seoul</option>
        <option value="America/New_York">America/New_York</option>
    </select>
    <select name="format">
        <option value="Y-m-d H:i:s">Y-m-d H:i:s</option>
        <option value="Y-m-d">Y-m-d</option>
    </select>
</form>
<input type="button" id="execute" value="execute" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $('#execute').click(function(){
        $.ajax({
            url:'./time2.php',
            type:'post',
            data:$('form').serialize(), //form 태그의 정보를 '값의이름=값의내용&값' 형식으로 바꿔줌
            success:function(data){
                $('#time').text(data);
            }
        })
    })
</script>
cs

 


JSON 처리

[time3.php]

1
2
3
4
<?php
$timezones = ["Asia/Seoul""America/New_York"];
echo json_encode($timezones);
?>
cs

 

[demo3.html]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<p id="timezones"></p>
<input type="button" id="execute" value="execute" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $('#execute').click(function(){
        $.ajax({
            url:'./time3.php',
            dataType:'json',
            success:function(data){
                var str = '';
                for(var name in data){
                    str += '<li>'+data[name]+'</li>';
                }
                $('#timezones').html('<ul>'+str+'</ul>');
            }
        })
    })
</script>
cs

+ Recent posts