xhr.js
xhr.js is a library(< 2Kb) to make AJAX/HTTP restful requests with XMLHttpRequest. It has similar API with Python-requests.
Usage
1. Install xhr.js
```sh
npm install xhr.js
```
2. import xhr.js
UMD import is supported, then get global object: XHR
.
```js
import XHR from 'xhr.js';
// or
var XHR = require("xhr.js");
```
or link with script
in html files:
```js
```
3. use class XHR
```js
var xhr = XHR(async); // default is async. you can set sync use XHR(false)
xhr.on('success', function(result) {
console.log('status_code:', result.status_code);
console.log('status_text:', result.status_text);
console.log('response_type:', result.response_type);
console.log('text:', result.text);
console.log('headers:', result.headers());
console.log('json:', result.json()); // get the json result.
console.log('xml:', result.xml());
});
xhr.get('package.json', params={'a': 'b'});
```
Detail API
- XHR API
xhr.request(method, url, body, onsuccess, onfail)
: request the url, with the method.
xhr.on()
: 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.
- XHR Event
ready
: whenxhr
is ready.
error
: whenxhr
can not be ready.
success
: whenstatus_code is 200
.
fail
: whenstatus_code is not 200
.
- Response API (result)
result.text
: get all response text;
result.status_code
: the server response code;
result.status_text
: the server response code text, e.g.ok
(status code is200
).
result.response_type
: response type;
result.json
: get the json object of response text;
result.xml
: get the xml object of response text;
result.headers
: get all the response headers object;
TODO
- request auth
- delete, put
- a http test chrome plugin, like postman.
LICENSE
MIT