1.0.0 • Published 11 years ago
requests.js v1.0.0
requests.js
Asynchronous HTTP request library. Tiny wrapper for XMLHttpRequest.
Usage
HTML:
Requests.request("GET", "/posts.html", {
success: function(response) {
document.body.innerHTML = response;
}
});JSON:
Requests.request("GET", "/posts.json", {
success: function(response) {
console.log(JSON.parse(response));
}
});JSON (with dataType):
Requests.request("GET", "/posts.json", {
dataType: "json",
success: function(json) {
console.log(json);
}
});Query String:
// GET http://localhost/posts?foo=bar
Requests.request("GET", "/posts", { params: { foo: "bar" }});Post parameters:
Requests.request("POST", "/posts", { data: { foo: "bar" }});Post form:
var form = document.getElementById("post-form");
Requests.request("POST", "/posts", { data: new FormData(form) });Post JSON:
Requests.request("POST", "/posts.json", {
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
data: JSON.stringify({
foo: "bar"
})
});File Upload:
var input = form.querySelector("[type=file]");
var form = new FormData();
form.append("post[file]", input.files[0]);
form.append("post[title]", "New post");
Requests.request("POST", "/posts", { data: form });Defaults
var csrfToken = document.querySelector("meta[name=csrf_token]").content;
Requests.defaults.headers["X-CSRF-Token"] = csrfToken;Full API:
Requests.defaults = {
headers: {},
params: null,
data: null,
dataType: "", /* arraybuffer, blob, document, json, text */
csrf: true, /* sets CSRF token from <meta name="csrf_token" content="token" />*/
success: function(response, xhr) {}, /* 20x status code */
error: function(response, xhr) {} /* ! 20x status code */
}
Requests.request("GET", "/url", options);Browser Support
![]() | ![]() | ![]() | ![]() | ![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |




