항해99

항해 2일차 TIL - ajax에 들어가는 property들은 어떤 의미일까요?

자몽포도 2022. 12. 7. 00:14

오늘은 ajax 통신에 대한 정리를 해보려고 한다.

물론 IDE의 로그를 보거나 브라우저의 콘솔을 보면 오류를 해결할 수 있지만!,

ajax 통신에 대해 알고 있으면 더 빠르게 오류를 해결할 수 있는 접근을 할 수 있을 것 같았습니다.

$.ajax({
    type: "POST",
    url: "/sign",
    data: {email_give: emailVal, pw_give: pwVal, 
        nick_give: nicknameVal, lang_give: langVal, blog_give: blogVal},
    success: function(response){
    // 로직...

ajax는 뭐고.. 안에 들어가는 type ,url , success 들은 뭐지?? 그리고 data는 왜 들어갈 떄도 있고 안들어갈때도 있는거야?

 

 

 

WHAT

오류가 발생했는데 ajax에 대해 잘 몰라 팀원에게 잘 설명해주지 못했어요.

HOW 

ajax를 찾아보고 예제를 통해 조금 정리하였습니다.

 

ajax란?

Asynchronous JavaScript and XML

비동기적 정보교환기법, 자바스크립트와 XML을 이용한. 굳이 XML은 아니어도 된다. 데이터의 형태면 된다.

 

비동기란?

비동기 : 요청과 응답이 동시에 일어나지 않는다. 그래서 요청하고 딴 짓을 할 수 있다.

동기 : 요청과 응답이 동시에 일어난다. 더 이해하기 쉽게 말하면 요청과 응답이 동시에 일어나야 한다. 정도로 해석하면 될 것 같다. 그 예로 Java의 Scanner를 통해 입력을 요청받으면 응답받기 전까지 딴 짓을 할 수가 없다.

 

ajax 통신을 하는 방법은 여러가지가 있다.

1. jquery 2.fatch 3. axios

팀 프로젝트에서는 jquery를 이용한 방법을 사용하니 이를 기준으로 설명해보겠습니다.

jquery - $.ajax(settings)

jQuery를 이용한 ajax 통신의 가장 기본적인 API

주요 property

  • data : 서버에 전송할 데이터, key/value 형식의 객체
  • contentType : 서버가 리턴하는 데이터 타입(xml, json, script, html)
  • type : 서버로 전송하는 데이터의 타입(POST, GET)
  • url : 데이터를 전송할 URL
  • success : ajax 통신에 성공했을 때 호출될 이벤트 핸들러

 

GET 방식

// js
function show_profile(){
$.ajax({
    type: 'GET',
    url: '/profile',
    data: {},
    success: function (response)

 

#python
@app.route('/profile', methods=["GET"])
def profile():
    profile_list = list(db.members.find({}, {'_id': False}))
    return jsonify({'profile': profile_list})

1. js show_profile() : /profile에 접속할게 데이터 부탁해.

2. python profile() 작동하고 profile_list를 response 담아 보낸다.

3. js show_profile() success 부분이 수행된다.

 

 

POST 방식

//js

function check_sign(){
    let emailVal = $('#input-email').val();
    let pwVal = $('#input-pw').val();
    let nicknameVal = $('#input-nickname').val();
    let langVal = $('#input-lang').val();
    let blogVal = $('#input-blog').val();
$.ajax({
    type: "POST",
    url: "/sign",
    data: {email_give: emailVal, pw_give: pwVal, nick_give: nicknameVal, lang_give: langVal, blog_give: blogVal},
    success: function(response){

 

@app.route("/sign", methods=["POST"])
def sign_post():
    email_receive = request.form['email_give']
    passwd_receive = request.form['pw_give']
    name_receive = request.form['nick_give']
    lang_receive = request.form['lang_give']
    blog_url_receive = request.form['blog_give']

    member_list = list(db.members.find({}, {'_id': False}))
# 이하 로직 생략
    doc = {
        'email': email_receive,
        'passwd': passwd_receive,
        'name': name_receive,
        'lang': lang_receive,
        'blog_url': blog_url_receive
    }
# 이하 로직 생략
    db.members.insert_one(doc)

 

ajax 통신에서 POST 방식은 브라우저에 어떠한 데이터를 form, input에 담아 보낼때 사용하는 경우가 많은 것 같다.

 

1. 클라이언트가 input-email, input-pw 등을 담아 특정 버튼을 보내면 js check_sign() 함수 호출

2. '/sign' url에 해당하는 API(python의 sign_post()) 호출

3. 주요 로직은 db에 저장 완료

 

 

SO

틀린 부분이 있을 수도 있지만 제가 느낀 ajax를 이해하는 쉬운 방법은 type으로 나누는 것이었습니다.

 

GET 요청의 경우

브라우저가 서버의 데이터를 요청하는 경우가 많다.

그래서 ajax data property 가 공백이고  response의 데이터를 받아 어떠한 로직을 수행한다.

 

POST 요청의 경우

브라우저가 어떠한 데이터를 담아 서버에 요청한다. 예를 들면 저장, 검색 등이 있을 것이다.

그래서 akax data property에 data가 담기는 경우가 많다.