Javascript

Ajax

breeghty 2023. 2. 23. 16:58

데이터의 url과 get, post 통신방식 기재시 서버에서 데이터를 읽어오거나 원하는 데이터를 보낼 수 있다.

-get 데이터를 받아서 읽고 싶을 때

-post 데이터를 보내고 싶을 때

이 경우, 매번 브라우저의 새로고침이 필요하다.

 

ajax 기능을 이용하면 데이터를 주고 받을 때 브라우저를 새로고침하지 않을 수 있다.

=> 새로고침 없이 get, post 요청하는 기능이다.

 

jQuery로 url에 get, post 요청하는 방법

jquery

//ajax get
$.get('https://~~')
.done(function(data){
    //성공시
    console.log(data);
    //서버에서 받아온 데이터는 == data
}).fail(function(){
    //실패시
    console.log("실패");
})

//ajax post
$.post('url~',보내고 싶은 데이터)
.done(function(data){
    console.log(data);
    //서버에서 받아온 데이터는 == data
});

vanilla javascript로 url에 get요청하는 방법

fetch('https://~~.json')
.then(res => res.json()) //받아온 json을 object로 바꿔주는 기능.(jquery는 자동변환)
.then(data => {
    console.log(data);
})
.catch(error => {
    console.log(error);
})