본문으로 바로가기

jQuery Ajax 다루기 -1 : GET / POST

category Language/Javascript 2020. 7. 28. 14:02

Ajax 

  • Ajax(Asynchronous JavaScript and XML, 에이잭스)는 비동기적인 웹 애플리케이션의 제작을 위해 아래와 같은 조합을 이용하는 웹 개발 기법이다.
  • 표현 정보를 위한 HTML (또는 XHTML) 과 CSS
  • 동적인 화면 출력 및 표시 정보와의 상호작용을 위한 DOM, 자바스크립트
  • 웹 서버와 비동기적으로 데이터를 교환하고 조작하기 위한 XML, JSON 등을 이용할 수 있다.

 

장점

  • 페이지 이동없이 고속으로 화면을 전환할 수 있다.
  • 서버 처리를 기다리지 않고, 비동기 요청이 가능하다.
  • 수신하는 데이터 양을 줄일 수 있고, 클라이언트에게 처리를 위임할 수도 있다.

단점

  • Ajax를 쓸 수 없는 브라우저에 대한 문제가 있다.
  • HTTP 클라이언트의 기능이 한정되어 있다.
  • 페이지 이동없는 통신으로 인한 보안상의 문제
  • 지원하는 Charset이 한정되어 있다.
  • 스크립트로 작성되므로 디버깅이 용이하지 않다.
  • 요청을 남발하면 역으로 서버 부하가 늘 수 있음.
  • 동일-출처 정책으로 인해 다른 도메인과는 통신이 불가능하다.

 

Ajax 는 새로고침하지 않고도 비동기 요청으로 동적인 화면 출력이 가능합니다.

 

GET / POST

서버에 HTTP GET 방식으로 요청할 때 사용합니다.

다음 두가지 표현으로 사용할 수  있습니다.

 

$.get/post( url, data, success(data, textStatus), dataType

  • url: 요청 url
  • data: 요청 data (string, map)
  • success: 요청 성공시 실행되는 callback 함수
  • dataType: 서버에서 응답받고자하는 데이터 타입 (xml, json, script, text, html)

 

$.ajax

$.ajax({
    // type: get,
    // type: post
    url: url,
    data: data,
    success: success,
    dataType: dataType
});

 

예제

기본적인 TEXT, JSON 요청과 응답을 해보았습니다.

import json
from flask import Flask, render_template, make_response

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get_text')
def get_text():
    data = 'jvvp.tistory.com'
    return data
    # response = make_response(data)
    # response.content_type = 'text'
    # return response

@app.route('/get_json')
def get_json():
    data = json.dumps({'name': 'red', 'rgb': '(255, 0, 0)'})
    return data
    # response = make_response(json.dumps(data))
    # response.content_type = 'application/json'
    # return response

if __name__ == '__main__':
    app.run(debug=True)

flask

$("#text_btn").click(function(){
    $.get('/get_text', function(data, status){
            alert('status: ' + status + '\ndata: ' + data);
    }, 'text');
    // $.ajax({
    //     // type: 'GET',
    //     url: '/get_text',
    //     // dataType: 'text',
    //     success: function(data){
    //         alert(data);
    //     }
    // });
});

$("#json_btn").click(function(){
    // $.get('/get_get_json', function(data, status){
    //     alert('status: ' + status + '\ndata: ' + data);
    // }, 'json');

    $.ajax({
        type: 'GET',
        url: '/get_json',
        // dataType: 'json',
        success: function(data){
            alert(data);
        }
    });
});

js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax</title>
</head>
<body>
    <button id='text_btn''>TEXT 데이터 요청</button>
    <button id='json_btn'>JSON 데이터 요청</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <script src="static/js/index.js"></script>
</body>
</html>

index.html

 

 

TEXT 데이터 요청

@app.route('/get_text')
def get_text():
    data = 'jvvp.tistory.com'
    return data
    # response = make_response(data)
    # response.content_type = 'text'
    # return response

flask

$("#text_btn").click(function(){
    $.get('/get_text', function(data, status){
            alert('status: ' + status + '\ndata: ' + data);
    }, 'text');
    // $.ajax({
    //     // type: 'GET',
    //     url: '/get_text',
    //     // dataType: 'text',
    //     success: function(data){
    //         alert(data);
    //     }
    // });
});

js

 

 

JSON 데이터 요청

 

@app.route('/get_json')
def get_json():
    data = json.dumps({'name': 'red', 'rgb': '(255, 0, 0)'})
    return data
    # response = make_response(json.dumps(data))
    # response.content_type = 'application/json'
    # return response

flask

$("#json_btn").click(function(){
    // $.get('/get_get_json', function(data, status){
    //     alert('status: ' + status + '\ndata: ' + data);
    // }, 'json');

    $.ajax({
        type: 'GET',
        url: '/get_json',
        // dataType: 'json',
        success: function(data){
            alert(data);
        }
    });
});

js