서버에 요청하는 법
- 어떤 데이터인지 url을 제대로 작성한다 (틀린 url로 요청시 404error가 뜬다)
- 어떤 방법으로 요청할지 결정한다 (GET/POST .. PUT, DELETE 등)
GET
GET 요청은 서버에 있던 데이터를 읽고 싶을 때 주로 사용한다.
브라우저 주소창에 url을 적으면 그곳으로 GET 요청을 날린다.
POST
POST 요청은 서버로 데이터를 보내고 싶을 때 주로 사용한다.
POST 요청을 날리고 싶으면 form 태그 + method="post" + action="url"을 이용하면 된다.
<form action="/data" method="post">
</form>
GET과 POST는 요청하면 브라우저가 새로고침된다.
AJAX
서버에 GET, POST 요청을 할 때 새로고침 없이 데이터를 주고받을 수 있게 도와주는 브라우저 기능이다. (ex. 댓글을 서버로 전송하거나, 목록 펼쳐 더보기 등)
데이터 요청하기
기본함수는 fetch(), jquery는 $.get() 안에 url을 기입한다.
then()(혹은 done())안에 콜백함수 넣고 파라미터를 만들면 데이터 요청 성공시 거기에 데이터가 들어간다. (요청 성공시 done 안에 있는 코드를 실행해준다.)
요청 실패시 catch(혹은 fail()) 안에 있는 코드를 실행해준다.
// 자바스크립트 기본함수 버전
fetch('https://codingapple1.github.io/price.json')
.then(res => res.json())
.then(function(data){
console.log(data)
})
.catch(function(error){
console.log('실패함')
});
원래 서버와 데이터를 주고받을 때는 문자만 주고받을 수 있기 때문에 array, object 등이 전송이 불가능하다. 그렇기 때문에 JSON으로 바꿔서 전송할 수 있다. (JSON은 문자로 인식하기 때문에 서버와 데이터주고받기가 가능하다)
// jquery 버전
$.get('https://codingapple1.github.io/hello.txt')
.done(function(data){
console.log(data)
})
.fail(function(error){
console.log('실패')
});
jquery의 $.get()은 JSON으로 자료가 도착하면 알아서 array/object 자료로 바꿔준다. 그러나 기본함수 fetch() 등은 JSON으로 자료가 도착하면 res.json() 코드를 넣어주어야 array/object 자료로 바꿀 수 있다.
JSON을 object로 변환하기
https://sunshineyellow.tistory.com/53
[드림코딩] JSON to Object (parse)
JSON to Object parse(json) const coder = { name: 'Noran', language: 'Javascript', height: null, birthDate: new Date(), sayhi: () => { console.log(`Hello, I'm ${name}!`); }, }; console.clear(); json = JSON.stringify(coder); const obj = JSON.parse(json); con
sunshineyellow.tistory.com
데이터 보내기
$.post('url~~', {name : 'Noran'})
post도 .done()을 붙이는 등 가능하다.
object를 JSON으로 변환하기
https://sunshineyellow.tistory.com/52
[드림코딩] Object to JSON (stringify)
Object to JSON stringify(obj) stringify는 데이터를 string타입으로 변환한다. let json = JSON.stringify(true); console.log(json); //"true" let json = JSON.stringify(['Noran','Paran']); console.log(json); //["Noran","Paran"] 한개의 single quot
sunshineyellow.tistory.com
출처 : 코딩애플 https://codingapple.com/ / MDN https://developer.mozilla.org/ko/
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [제로초] Promise와 동기/비동기 관련 짤막 키워드정리 (0) | 2023.09.06 |
|---|---|
| [코딩애플] Local Storage 사용법 (Session Storage, IndexedDB, Cookies, Cache Storage) (0) | 2023.04.13 |
| [mdn, 코딩애플 등] for, forEach, for in (1) | 2023.01.31 |
| [코딩애플,mdn] js로 html 생성하는 법 (appendChild, createElement, insertAdjacentHTML 등) (0) | 2023.01.18 |
| [코딩애플] 자료형 : Array, Object (특징과 차이점) (0) | 2023.01.18 |