Skip to content

Instantly share code, notes, and snippets.

@redgoose-dev
Last active December 6, 2019 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redgoose-dev/c653909c7716fc272ad634f76bc5478d to your computer and use it in GitHub Desktop.
Save redgoose-dev/c653909c7716fc272ad634f76bc5478d to your computer and use it in GitHub Desktop.
비동기 통신을 위한 `XMLHttpRequest` 객체의 인터페이스
/**
* ajax
* 비동기 통신을 위한 `XMLHttpRequest` 객체의 인터페이스
*
* @param {string} url
* @param {string} method
* @param {object} data `xhr.send()` 메서드의 인자값. `formData`같은값을 넣음
* @param {function} progress 통신중에 호출되는 함수
* @param {function} before 통신을 시작하기전 xhr 객체를 추가 조작을 위한 중간에 실행하는 함수로 사용할 수 있다.
* @return {promise}
*/
export function ajax(url='', method='get', data=null, progress, before)
{
return new Promise(function(resolve, reject, notify) {
if (!XMLHttpRequest) reject(`Not support browser`);
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
if (this.status === 200 || this.status === 201)
{
resolve(this.responseText);
}
else
{
reject(this.responseText);
}
});
xhr.addEventListener('error', function() {
reject('error request');
});
if (progress && typeof progress === 'function')
{
xhr.addEventListener('progress', progress);
}
xhr.open(method, url);
if (before && typeof before === 'function') before(xhr);
xhr.send(data);
});
}
// simple example
ajax('https://address.com', 'get').then(function(res) {
// complete area
});
// example formdata
let formData = new FormData();
ajax(
// url
'https://address.com',
// method
'post',
// data
formData,
// progress
function(xhr) {
const percent = xhr.loaded / xhr.total;
console.log(`loaded: ${percent}%`);
}),
// before
function(xhr) {
xhr.setRequestHeader();
}
).then(function(res) {
// complete area
}).catch(function(error) {
// error area
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment