Archive

[JS] Ajax

livemehere 2021. 11. 1. 02:10

원레 html에서, 웹에서 Rest통신을 하려면, form을 사용해야하고, 새로고침이됬어야했다(새로운페이지로 라우팅).

하지만 Ajax는 비동기적으로, Rest통신을 하고, 값을 받아와서, 좀더 부드럽고,동적인형태가 가능해졌다

 

새로고침 없이 서버에서 데이터를 받아오는 것이다

 

jQuery로 Ajax요청하기 

 

Ajax요청을 하는 법은 쉽습니다. $.ajax() 라는 함수를 쓰고 안에 {} 오브젝트 형식으로 몇개만 셋팅해주시면 됩니다. 

 

$.ajax({ 
    url : 'https://naver.com',
    type : 'GET'
});

{} 오브젝트 안에는 url, type 이 두개가 필수로 들어갑니다.

url 정보란엔 데이터 요청할 서버 URL, 

type 정보란엔 요청의 종류를 적어주시면 됩니다. 

그럼 위의 코드는 naver.com에다가 GET요청을 하는 코드입니다.

 

요청결과(데이터)를 출력해보기 

$.ajax({ 
    url : 'https://codingapple1.github.io/hello.txt',
    type : 'GET'
}).done(function(데이터){
  console.log(데이터);
});

Ajax에 추가로 들어갈 수 있는 내용들이 많습니다.

$.ajax({ 
    url : 'https://codingapple1.github.io/hello.txt',
    type : 'GET',
    data : '어쩌구',
    dataType : '저쩌구'
});
$.ajax({ 
    url : 'https://codingapple1.github.io/hello.txt',
    type : 'GET'
}).fail(function(){
  //요청이 실패했을 때 실행할 코드 
}).always(function(){
  //실패하든 성공하든 항상 실행할 코드
})
$.ajax({ 
    url : 'https://이상한URL.com',
    type : 'GET'
}).fail(function( jqXHR, textStatus, errorThrown ){
  console.log(errorThrown)
})

 

반응형