[Ajax] ajax를 이용한 비동기방식

윤찬효·2023년 5월 29일
0

11주차

목록 보기
5/6

ajax 문서


ajax를 이용하여 통신을 하고, html 일부만 리로드하는 내용

function ajaxExample() {
    $.ajax({
        url : 'url',
        type : "POST",
        headers: {
            'Authorization': 'Bearer ' + 'access 토큰',
        },
        success: function(data){
            console.log(data)
        }
    })
}

ajax를 통해 POST 통신하는 방식이며, url에서 받아온 값(data)를 가공하여 html에 노출 시켜준다.


ajax 사용하여 작성한 코드 공유

// ajax를 이용한 팔로우 기능 추가
function userFollow() {
    const urlParams = new URL(location.href).searchParams;
    const profile_id = urlParams.get('id');
    const follow_button = document.getElementById("follow_button")

    $.ajax({
        url : 'http://127.0.0.1:8000/users/follow/'+profile_id+'/',
        type : "POST",
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem("access"),
        },
        success: function(data){
            if(data === "follow") {
                follow_button.innerText = "팔로우 취소"
                console.log(data)
            }
            else {
                follow_button.innerText = "팔로우"
                console.log(data)
            }
        }
    })
}

0개의 댓글