본문 바로가기
Script/Javascript

jquery ajax 사용방법 예제

by 애플 로그 2022. 7. 20.
반응형

jquery ajax 사용방법 예제

jqeury 가 뭔지도 모르는 사람도 따라할수 있게 처음부터 정리한다.

1. Jquery import 하기

jquery ajax 사용하기 위해서는 jquery를 import 해야한다.

jquery 파일을 다운로드 받아서 파일형태로 import를 해도 좋고, 아래 CDN 을 이용해도 좋다.

서비스를 할 것이면, 다운로드해서 import 하고 테스트용이라면 CDN을 이용해도 문제없어 보인다.

 

jquery 다운로드

jquery 공식홈페이지로 이동해서 다운로드 할수 있습니다.

jQeury 공식홈페이지 다운로드 (클릭)

 

 

구글 CDN 사용하기

3.x snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
2.x snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
1.x snippet:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

 

 

아래와 같은 코드로 html 구성이 되었다면 jquery는 사용할 준비는 되어 있다고 보면된다.

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript"> 
    
    </script>
  </head> 
</html>

 

2. ajax 기본 전송 - method : GET

화면이 로그 된뒤에 get 방식으로 sendPage.jsp 라는 곳에 

page, no, name 과 같은 파라미터를 가지고 호출 하는 예제 이다.

( sendPage.jsp 는 지금 내가 호출하고 있는 페이지와 도메인이 같아야한다. cross domain 정책 !! )  

<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      $.ajax({
        type: "GET",
        url: "sendPage.jsp?page=1&no=3&name=user01",
        dataType: "text",
        contentType : "application/x-www-form-urlencoded;charset=UTF-8"
        error: function() {
          console.log('통신실패!!');
        },
        success: function(data) {
          console.log("통신데이터 값 : " + data);
        }
      });
    });
  </script>
</head>
<body></body>

</html>

 

ajax 호출 속성 설명

type : http 전송 method를 지정한다.

url : 호출 URL 지정

dataType : Ajax를 통해 호출한 페이지의 return 형식

error : 에러났을때 처리하는 함수

success : 성공했을때 처리하는 함수

 

 

3.  응용  - 유저가 입력한 데이터를 API 서버로 호출하는 예제

API스펙은 아래와 같다고 상상 해보자

method : post

contentType : application/json 

    function sendData(){
      
      var data ={};
      data.email = $('#email').val();
      data.phone = $('#phone').val();
      
      var jsonStr = JSON.stringfy(data);
      
      	$.ajax({
        type : 'post',
        url : url,
        data : jsonStr,
        contentType : "application/json; charset=utf-8",
        error : onError,
        success : onSuccess
	  });
  }

서버에서 JSON 데이터를 받으므로 JSON.stringfy 와같은 변환이 필요하고,

contentType을 application/json 으로 설정하였다.

 

 

※ javascript를 웹페이지에서 간편하게 바로 테스트 해볼수 있습니다.

아래 포스팅도 함께 확인해 보시기 바랍니다.

 

[Script/Javascript] - javascript 테스트 사이트

 

javascript 테스트 사이트

javascript 테스트 사이트 말그대로 web에서 바로 script구문을 짜서 테스트 해볼수 있는 사이트가 있다. html ,css ,javascript 바로 짜서 result 결과 화면에서 확인해볼수 있다. 저장후 URL을 공유해 타인에

www.appletong.com

 

댓글