Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- select by attribute
- es6
- css
- css 오버레이
- ajax
- express-handlebars
- 정규표현식
- flex-basis
- Engoo
- css grid
- Sass
- Node.js
- css variables
- flex-shrink
- 디자인패턴
- Object.create
- regExp
- close together
- img 확대
- node
- JS
- just-one-small-sip
- 무료 백엔드 배포
- shit-christmas
- module wrapper function
- flex-grow
- Express
- Prototype
- improve-iq-by-up-to-10%!
- flexbox
Archives
- Today
- Total
AJAX 이용 시 주의할 점 본문
1. onload 콜백함수 내부에서 this 사용
...
// onload에 할당된 함수가 callback 함수로 이용되기 때문에 실제 동작시 this가 가리키는 객체가 달라짐에 주의하자.
let self = this;
this.http.onload = function () {
// if (this.http.status === 200) <=== error
if (self.http.status === 200) {
return self.http.responseText;
}
};
...
2. 비동기 요청의 결과를 리턴 받을 때
const easyHttp = new EasyHttp();
const posts = easyHttp.getRequest("https://jsonplaceholder.typicode.com/posts", null);
console.log(posts); // undefined, 즉 위의 작업이 끝나지 않고 해당 라인이 실행됨
따라서 아래와 같이 콜백함수를 이용한다.
const easyHttp = new EasyHttp();
easyHttp.getRequest("https://jsonplaceholder.typicode.com/posts", getPosts);
function getPosts(posts) {
console.log(posts);
}
3. 콜백함수 작성 시 error를 대비하자
const easyHttp = new EasyHttp();
easyHttp.getRequest("https://jsonplaceholder.typicode.com/posts", getPosts);
// error 인자를 만들어서 error handling이 가능하도록 작성
function getPosts(error, posts) {
if (error) {
console.log(error);
} else {
console.log(posts);
}
}
'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글
ES6 Promise (0) | 2021.06.09 |
---|---|
AJAX POST request (0) | 2021.06.07 |
Callback function (0) | 2021.06.07 |
REST API (0) | 2021.06.07 |
XHR object를 이용한 비동기 통신 (0) | 2021.06.07 |
Comments