3.0.2 • Published 8 years ago
simple-xhr v3.0.2
simple-xhr
Very simple promise based ajax
- tiny
- Promise based (use polyfill if you need)
- supports aborting
- uses addEventListener (IE9+)
Important
- fetch is better ;) polyfill: whatwg-fetch
Installation
npm install --save simple-xhr
Usage
'Simple'
var ajax = require('simple-xhr');
ajax('/file.json', {
cache: false
})
.then(JSON.parse)
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.error(err);
});
Other methods
Default only load
and error
events are handled (useDefaultLoadEvent
, useDefaultErrorEvent
)
var ajax = require('simple-xhr');
ajax('/file.json', {
cache: false,
xhr: function(config, resolve, reject) {
// this is instance of XMLHttpRequest
// config is config ;)
// use resolve, reject for promise interaction
this.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total);
}
});
this.addEventListener('progress', function(e) {
if (e.lengthComputable) {
console.log(e.loaded / e.total);
}
});
this.addEventListener('loadstart', function(e) {
console.log('loadstart', this, e);
});
this.addEventListener('timeout', function(e) {
reject('timeout');
});
}
})
.then(JSON.parse)
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.error(err);
});
Aborting
var ajax = require('simple-xhr');
var abortObj = {};
ajax('test.json?fff&g=1', {
cache: 0,
headers: [
['X-Requested-With', 'XMLHttpRequest'], // pass default header if you add custom
['X-Secret', '666'] // custom
],
xhr: function(config, resolve, reject) {
this.addEventListener('abort', function(e) {
reject(new Error('aborted'));
});
this.addEventListener('loadstart', function(e) {
console.log('loadstart', this, e);
});
}
}, abortObj)
.then(JSON.parse)
.then(console.log.bind(console))
.catch(console.log.bind(console));
// it takes too long, kill it
abortObj.abort();
Load multiple (Promise.all)
var ajaxAll = require('simple-xhr').all;
ajaxAll.all(['/1.html', { method: 'post' }], ['/2.html', { cache: false }], '/3.html')
.then(console.log.bind(console))
.catch(console.log.bind(console));
Defaults
ajax.defaults = {
useDefaultLoadEvent: true,
useDefaultErrorEvent: true,
method: 'get',
mergeHeaders: false, // set to true for merging passed with defaults (array concat)
data: '', // urlencoded
responseType: '',
cache: true,
headers: [
['X-Requested-With', 'XMLHttpRequest']
],
postType: 'application/x-www-form-urlencoded', // or 'multipart/form-data'
timeout: 0, // ms
xhr: null
}
Protip (LOL): change defaults
var ajax = require('simple-xhr');
ajax.defaults.headers = [
['X-Requested-With', 'XMLHttpRequest']
['x-secret', 'youtu.be/dQw4w9WgXcQ'] // custom
];
Other exported stuff: all (basically Promise.all)
ES5, ES6, UMD (CommonJS, AMD, global)
- ES5
simple-xhr
orsimple-xhr/es5/simpleXHR
- ES6
simple-xhr/es6/simpleXHR
- UMD
simple-xhr/es5-umd/simpleXHR
(global:window.simpleXHR
)
Promise polyfill
npm install es6-promise --save