> For the complete documentation index, see [llms.txt](https://leeans-dev-book.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leeans-dev-book.gitbook.io/docs/lecture/javascript/ajax1.md).

# Ajax1

Ajax (Asynchronous JavaScript and XML) 는 서버와 데이터를 주고 받는 방법 중 하나.

## 서버란?

<figure><img src="/files/BMo8uNmmAEktUbMKTDuQ" alt=""><figcaption></figcaption></figure>

간단하게 말해서 사용자(클라이언트)가 요청하면 해당 요청(Request)에 대한 응답(Response)를 반환&#x20;

1. 웹브라우저(클라이언트)가 웹서버에 '[www.naver.com](http://www.naver.com)' 사이트 데이터 달라고 요청
2. 웹서버는 해당 사이트의 파일을 찾아서 웹브라우저에 반환
3. 웹브라우저는 파일을 받아 네이버 메인화면을 표시&#x20;

## GET / POST

GET 요청은 서버에 있던 데이터를 읽어올 때 주로 사용하고&#x20;

POST 요청은 서버로 데이터를 보낼 때 주로 사용함.

(예시.  서버로 보낸 데이터를 DB에 저장할 때)

PUT, PATCH, DELETE 도 있지만 지금은 GET / POST만 알고 갑시다.

&#x20;

GET 요청의 가장 쉬운 방법은 브라우저 주소창&#x20;

&#x20;[www.youtube.com](http://www.youtube.com) - 이 URL을 주소창에 적으면 해당 서버로 GET 요청을 날려줌.

POST 요청은 보통 html의 \<form> 태그에 담아서 요청함.

&#x20;예시. \<form url="요청할url" method="post">&#x20;

이러한 GET / POST 요청은 <mark style="color:purple;">**브라우저가 새로고침**</mark>  된다는 단점이 있다.

## Ajax

Ajax는 웹페이지 전체를 새로고침 하지 않고 서버와 데이터를 주고 받는 기술

#### jQuery로 Ajax 요청하기

{% embed url="<https://github.com/HyeokjaeLee/korea-webtoon-api>" %}

한국 웹툰 API를 사용해서 Get 요청을 연습 해보자.

```javascript
$.get("요청할 url");   //get 요청 방법

 $.get('https://korea-webtoon-api.herokuapp.com/search?keyword=쿠베라')
        .done(function (data){
            console.log(data);  //요청이 완료되면 동작할 코드
        }).fail(function (error){
            console.log(error); //요청이 실패했을 때  동작할 코드 
        })always(function (){
            console.log("test"); //성공 실패에 관계없이 항상 동작할 코드 
        })

```

&#x20;done / fail 말고 then/ catch 써도 괜찮음

<figure><img src="/files/fJ4Bp0gptOJz8A7hyy6u" alt=""><figcaption><p>위에서 요청한 webtoon API 결과 console 출력</p></figcaption></figure>

javascript 내장 라이브러리 fetch

```javascript
fetch('https://korea-webtoon-api.herokuapp.com/search?keyword=쿠베라')
  .then(res => res.json())
  .then(function(data){
    console.log(data)
  })
  .catch(function(error){
    console.log('실패함')
  });
```

이렇게 요청해도 결과는 똑같다.

코드가 한 줄이 더 필요한 이유는 서버와 데이터를 주고받을 때에는 문자만 주고 받을 수 있음

그런데 Ajax로 요청했을때에는 object 형태로 어떻게 받아온 거임?

&#x20;\>> jQuery의 $.get() JSON으로 데이터를 받아서 array/object 형태로 자료를 바꿔줌

내장함수 fetch는 그런게 없어서 res를 array/object로 바꾸기 위해 res => res.json() 이 코드가 필요함.

post 방식은&#x20;

```javascript
$.post('url', {title : 'Blosson Dress', price : 70000});  
```

이런식으로 보낼 url , 뒤에 data 적으면 가능함.

post방식도 .done .fail 가능함.

✨ 과제. js013.html 에 get 방식으로 좋아하는 웹툰의 데이터를 받아와서 첫번째 상품 이미지와 타이틀에

해당 썸네일과 웹툰 제목을 넣어보자.

🎈HINT img src 변경하는 법&#x20;

&#x20;  `$(img).attr("src", '이미지url');`

✨ 과제. 완료한 사람은 웹툰 제목 클릭하면 해당 url로 이동하게도 해보자.&#x20;

코드 따라치지말고 꼭 완료하고 확인해봅시다.

```javascript
$.get('https://korea-webtoon-api.herokuapp.com/search?keyword=쿠베라')
        .done(function (data){
            console.log(data);
            var webtoon = data.webtoons[0];
            console.log(webtoon);
            $('img').eq(0).attr("src", webtoon.img);
            $('.title').eq(0).html(webtoon.title);
           
            $('.title').on('click', function (){
                $(location).attr("href", webtoon.url);
            })
        }).fail(function (error){
            console.log(error);
        }).always(function (){
            console.log("test");
        })

```
