HTML, CSS, JavaScript/AJAX

[ajax] response 다루기(text, json) + JSON.parse()

망고고래 2024. 11. 7. 14:45

1. response.text()

fetch(url)
    .then(response => response.text())
    .then(text => {
        console.log(text);
    });

- 서버 응답을 문자열로 받음

- JSON, HTML 상관없이 모든 응답을 문자열로 처리

- Promise 반환

 

2. response.json()

fetch(url)
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

- json으로 온 서버 응답을 자바스크립트 객체로 파싱

- 내부적으로 JSON.parse() 실행

- 응답이 JSON 형식이 아닐 경우 에러 발생

- Promise 반환

 

 

+ JSON.parse()

fetch(url)
    .then(response => response.text())
    .then(text =>{
        const data = JSON.parse(text);
        console.log(data);
    });

- 문자열을 자바스크립트 객체로 변환

- response.text() 실행 후 JSON.parse()를 실행하면 response.json()과 결과가 같다.

'HTML, CSS, JavaScript > AJAX' 카테고리의 다른 글

[ajax] promise와 resolve(.then)  (0) 2024.11.07