본문 바로가기
Programming/JavaScript

[ JavaScript ] 자바스크립트 기본 문법 | jQuery Ajax

by 코뮤(commu) 2021. 2. 10.
728x90
반응형

이미지 출처 :      https://commons.wikimedia.org/wiki/File:JavaScript-logo.png

 

 

 

 

 

 

 

 

해당 포스팅은 생활코딩의 이고잉 님의 강의를 기반으로 개인 공부용으로 정리한 포스팅임을 미리 알립니다.

 

 

 


 

 

 

자바스크립트 기본 문법  ::  jQuery Ajax

 

 

 

 

jQuery이용해서 Ajax를 사용하게 되면 많은 이점이 있는데,

그 중의 하나가 크로스브라우징의 문제를 jQuery가 알아서 해결해준다는 것입니다.

 

뿐만 아니라 여러가지 편리한 기능들을 제공하는데,

이번 포스팅에서는 jQuery를 이용해서 Ajax 통신을 하는 법을 다루도록 하겠습니다.

 

 

 

 

자바스크립트 기본 문법  ::  $.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 with an error. This is an Ajax Event. Attach a function to be executed before an Ajax request is sent. This is an

api.jquery.com

 

 

위 링크는 Ajax 에 대한 jQuery API 가 들어있는 참고 문서 링크입니다.

 

 

 

 

 

그 중에서 가장 중요한 API는 $.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
    서버측에서 전송한 데이터를 어떤 형식의 데이터로 해석할 것인가를 지정합니다.

 

dataType의 값으로 올 수 있는 것은 xml, json, script, html입니다.

형식을 지정하지 않으면 jQuery가 알아서 판단해줍니다.

 

 

  • success
    성공했을 때 호출할 콜백을 지정합니다.
    Function( PlainObject data, String textStatus, jqXHR jqXHR )

 

  • type
    데이터를 전송하는 방법을 지정합니다. get, post를 사용할 수 있습니다.

 

 

 

이제 예제를 통해서 Ajax 통신을 진행해보도록 하겠습니다.

 

 

 

 

<?php
$d1 = new DateTime;
$d1->setTimezone(new DateTimezone("asia/seoul"));
echo $d1->format('H:i:s');
?>

 

 

 

<p>time : <span id="time"></span></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:'./time.php',
            success:function(data){
                $('#time').append(data);
            }
        })
    })
</script>

 

 

 

위의 코드는 ajax 포스팅 예제를 JQuery 화 한것입니다.

 

 

 

XMLHttpRequest 에 비해 코드가 훨씬 깔끔하고 간결해진 것을 알 수 있습니다.

 

 

 

POST 방식으로 통신을 할 때는 아래와 같이 처리합니다.

 

 

 

 

<?php
$d1 = new DateTime;
$d1->setTimezone(new DateTimezone($_POST['timezone']));
echo $d1->format($_POST['format']);
?>

 

 

<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(),
            success:function(data){
                $('#time').text(data);
            }
        })
    })
</script>

 

 

위의 코드에서,

 

아래 코드는 form 태그의 정보를 값의이름=값의 내용&값 의 형식으로 바꿔줍니다.

 

 

data:$('form').serialize(),

 

 

 

 

 

자바스크립트 기본 문법  ::  JSON 처리

 

 

$.ajax를 이용해서 JSON을 처리하는 방법을 알아봅시다.

 

 

 

<?php
$timezones = ["Asia/Seoul", "America/New_York"];
echo json_encode($timezones);
?>

 

 

 

<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>

 

 

 

dataType 을 json 으로 하면 됩니다.

 

 

 

 

 

728x90
반응형