xhr.js is a library(< 2Kb) to make AJAX/HTTP restful requests with XMLHttpRequest. It has similar API with
Python-requests
.
1. Install xhr.js
npm install xhr.js
2. import xhr.js
UMD import is supported, then get global object: XHR
.
import XHR from 'xhr.js';
// or
var XHR = require("xhr.js");
or link with script
in html files:
<script src="dist/xhr.min.js"></script>
3. use class XHR
var xhr = XHR(async); // default is async. you can set sync use XHR(false)
xhr.on('success', function(result) {
console.log('status:', result.status);
console.log('statusText:', result.statusText);
console.log('url:', result.url);
console.log('responseType:', result.responseType);
console.log('text:', result.text);
console.log('headers:', result.headers);
console.log('ok:', result.ok()); // get the json result.
console.log('json:', result.json()); // get the json result.
console.log('xml:', result.xml());
console.log('blob:', result.blob());
});
xhr.get('package.json', {'a': 'b'});
Another post
demo:
var xhr = XHR();
xhr.post('/post_url', {'a': 'b'}, function(r) {
r = r.json(); // get the json result.
// write your code
});
Upload file with FormData
object:
var fd = new FormData(document.querySelector('#submit_form'));
var xhr = new XHR();
xhr.post('/submit/new', fd, function(r) {
// request success
r = r.json();
console.log(r);
});
The API of xhr instance.
xhr.request(method, url, body, onsuccess, onfail)
: request the url, with the method.xhr.on(event_key, event_func)
: bind the request result(ready, error, success, fail), with result instance as it input.xhr.get(url, params, onsuccess, onfail)
: get request.xhr.post(url, params, onsuccess, onfail)
: post request.xhr.setRequestHeader(header_name, header_value)
: append a header.xhr.setAsync(aysnc)
: set request async / sync.xhr.url()
: get the request url.xhr.body()
: get the request body.xhr.abort()
: abort request.xhr.reset()
: reset the xhr instance, such url, headers, body, events.
The evnet keys is for API on
.
ready
: whenxhr
is ready.success
: whenstatus_code is 200
.fail
: whenstatus_code is not 200
.
The api is for request callback function paramter result
.
result.text
: get all response text;result.status
: the server response code;result.statusText
: the server response code text, e.g.ok
(status code is200
).result.responseType
: response type;result.headers
: get all the response headers object;result.ok()
: is request ok;result.json()
: get the json object of response text;result.xml()
: get the xml object of response text;result.blob()
: get the blob object of response text;
- request auth
- a http test chrome plugin, like postman.
MIT