# Ajax2

js015.html 파일을 생성하고 아래 코드를 붙여넣자.

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>

</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-sm-4">
                <img src="https://via.placeholder.com/600" class="w-100">
                <h5>Card title</h5>
                <p>가격 : 70000</p>
            </div>
        </div>
    </div>

    <script>
        var products = [
            { id : 0, price : 70000, title : 'Blossom Dress' },
            { id : 1, price : 50000, title : 'Springfield Shirt' },
            { id : 2, price : 60000, title : 'Black Monastery' }
        ];
    </script>

</body>
</html>
```

✨ 실습. \<div class="row"> 아래의 div 를 제거하고 script로 products의 갯수만큼 card 생성&#x20;

### 제발 직접 짜보기 🤣

```javascript
 products.forEach(function (item,index){
      $('.row').append(`<div class="col-sm-4">
           <img src="https://via.placeholder.com/600" class="w-100">
           <h5>${item.title}</h5>
           <p>가격 : ${item.price}</p>
       </div>`)
   });
```

✨ 실습. 상품더보기 버튼 누르면 Ajax 로 데이터 가져와서 콘솔창에 출력

데이터 가져올 서버는 아래 URL 사용&#x20;

<https://gist.githubusercontent.com/leeanJP/3ee931feb393f95895bd652344d1bf13/raw/d255a58907156433ef61de8401bf16564df4407f/more1.json>

가져온 데이터를 확인해보면 json 형태가 아닌 string으로 받아온다.

이럴때는 JSON.parse(string) 함수로  string > json 형변환을 할 수 있다.&#x20;

(이전에 parseInt parseFloat 함수 처럼 형변환을 위해 사용하는 것)

```javascript
$('#more').on('click',function (){
    $.get('https://gist.githubusercontent.com/leeanJP/3ee931feb393f95895bd652344d1bf13/raw/b65cef1db551c3815352418ca885fb0ff38684d5/more1.json')
        .done(function (result) {
            console.log(typeof result);
            console.log(result);
            var jsonData = JSON.parse(result)
            console.log(typeof jsonData);
            console.log(jsonData);

        }).fail(function (){
        console.log("에러 발생");
    })
})
```

✨ 실습. 위에서 가져온 데이터로 카드 3개 만들기

<pre class="language-javascript"><code class="lang-javascript"><strong>jsonData.forEach(function (item){
</strong>    $('.row').append(`&#x3C;div class="col-sm-4">
        &#x3C;img src="https://via.placeholder.com/600" class="w-100">
        &#x3C;h5>${item.title}&#x3C;/h5>
        &#x3C;p>가격 : ${item.price}&#x3C;/p>
        &#x3C;/div>`)
})
</code></pre>

지금은 서버와 DB가 따로 없어서 이런식으로 구현 했지만 나중에 데이터베이스와 java Spring

까지 배우고 나면 내 PC에 데이터베이스를 만들고 서버 프로그램을 구현해서 데이터를 가져오는 방식으로 프로그램을 짜게 될것임.

그렇게 하면 총 데이터의 갯수를 구하고, 처음에는 0번부터 19번까지 20개만 데이터를 가져오고 상품더보기를 클릭하면 상품더보기 버튼을 클릭한 횟수를 기억 했다가 20번부터 39번까지의 데이터를 가져오고 마지막에 가서는 상품 더보기 버튼을 숨기는 식으로 구현할 수 있다.&#x20;

이게 우리가 보는 쇼핑몰의 20개씩 상품보는 페이지의 작동방식&#x20;

20개씩 보기 > 50개씩 보기로 변경하면 가져오는 데이터 갯수만 변경하고 작동하는 방식은 같다.&#x20;

## 현업에서 사용하는 Ajax 코드 예제1&#x20;

```javascript
$.ajax({
    type : 'post',           // 타입 (get, post, put 등등)
    url : '/test',           // 요청할 서버url
    async : true,            // 비동기화 여부 (default : true)
    headers : {              // Http header
      "Content-Type" : "application/json",
      "X-HTTP-Method-Override" : "POST"
    },
    dataType : 'text',       // 데이터 타입 (html, xml, json, text 등등)
    data : JSON.stringify({  // 보낼 데이터 (Object , String, Array)
      "no" : no,
      "name" : name,
      "nick" : nick
    }),
    success : function(result) { // 결과 성공 콜백함수
        console.log(result);
    },
    error : function(request, status, error) { // 결과 에러 콜백함수
        console.log(error)
    }
})
```

## 현업에서 사용하는 Ajax 코드 예제2

```javascript
var httpFileUpload = {
    
    getAddr : function(fileElement, callback){
        
        const file = fileElement[0];
        if(!file){
            throw new Error("file Element is required");
        } else {    
            const uploadFile = file.files[0];
            
            if(!uploadFile || !uploadFile.size || !uploadFile.name || uploadFile.size === 0){
                throw new Error("upload file is required");
            } else {
                console.log("file size : " + uploadFile.size+"\nfile name : " + uploadFile.name);
                 
                var params = {
                        filename : uploadFile.name,
                        filesize : uploadFile.size,
                        provider : "TEST"
                    };
                
                $.ajax({
                    type    : "POST",
                    url        : "/sample.do",
                    contentType: "application/json",
                    dataType:"json",
                    data     : JSON.stringify(params)    
                })
                .done(function (data, textStatus, xhr) {
                    console.log(xhr);
                    if(data.result_cd == "1"){
                        alert("success!");
                    } else {
                        alert("에러발생["+data.result_cd+"]");
                        console.log(data.result_msg);
                        callback(data);
                    }
                })
                .fail(function(data, textStatus, errorThrown){
                    console.log("fail in get addr");
                    callback(data);
                });
            }
        }
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://leeans-dev-book.gitbook.io/docs/lecture/javascript/ajax2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
