[JS] Ajax

JeongChaeJin·2022년 7월 20일
0

JavaScriptStudy

목록 보기
17/22

서버와 데이터 주고 받는 법

Server

  • 데이터주라고하면 데이터보내주는 프로그램
  • 어떤 데이터인지(url), 어떤 방법(GET, POST)으로 요청할건지 잘 기재해줘야된다.
    • GET : 데이터 읽고 싶을 때 (브라우저에서 url 넣는 부분)
    • POST : 데이터 보내고 싶을 때
  • API Docs 유용
    <form action="sdfsdf" method="post">
        
    </form>
  • 이런식으로 action에 url 지정, method에 post, get 등을 지정해주면된다.
  • 단, GET/POST 요청 시 브라우저 새로 고침된다.

Ajax

  • 새로 고침 없이 GET, POST 요청하는 기능
$.get('https://codingapple1.github.io/hello.txt').
            done(function(data) {
                console.log(data);
            }).
            fail(function() {
                console.log("실패함");
            })
  • script tag에 위와 같은 동작을 코딩해주면 된다.

  • 코딩애플에서 만들어준 서버에 저렇게 get 요청해보자.

  • done : ajax에서 요청한 method 성공 시 실행된다.

  • fail : 요청 method 실패 시 실행된다.

$.post('https://codingapple1.github.io/hello.txt', {"name": lotto}).
            done(function(data) {
                console.log(data);
            })
  • post는 위 처럼 하면된다.
fetch('https://codingapple1.github.io/hello.txt').
            then(res => res.json()).
            then(data => {
                console.log(data);
            }).
            catch(error => {
                console.log(error);
            })
  • 쌩 javascript를 사용하려면, 위 구문을 사용하면된다.
  • 서버와 유저는 문자 자료만 주고 받을 수 있다.
    • object, array를 보내고 싶으면 따옴표 쳐서 문자처럼 만들어야된다.
    • "{key : value}"
    • 만약, 받아온 json이 object 일것이면 .json()으로 object 로 바꿔주는 기능을 사용하면된다. -> $.get()은 json 을 object로 바로 사용하게해준다.
  • axios 라이브러리로 ajax를 편하게 사용할 수도 있다. (vue, react)
    
    <div class="container">
        <button class="btn btn-danger" id="more">더보기</button>
    </div>

    <script>
        $('.more').click(function() {
            console.log(1);
            $.get("https://codingapple1.github.io/js/more1.json").
                done((products) => {
                    console.log(products);
                    products.forEach((product) => {
                        var template = 
                            `<div class="col-sm-4">
                                <img src="https://via.placeholder.com/600" class="w-100">
                                <h5>${product.title}</h5>
                                <p>가격 : ${product.price}</p>
                            </div>`;

                        $('.row').append(template);
                    })
                })
        })
    </script>
  • get method로 버튼 클릭 시 서버에 요청해서 그려주는 코드이다.
profile
OnePunchLotto

0개의 댓글