Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function xhr(options, cb) {
- if(!options) {
- throw '[ajax] missing required options';
- }
- var url = options.url ? options.url : window.location.href;
- var method = options.method ? options.method.toUpperCase() : 'GET';
- var data = options.data ? JSON.stringify(options.data) : null;
- var contentType = (typeof options.contentType !== 'undefined') ? options.contentType : null;
- var headers = (options.headers && typeof options.headers === 'object') ? options.headers : {};
- var username = options.username ? options.username : null;
- var password = options.password ? options.password : null;
- var timeout = options.timeout ? options.timeout : 0;
- var withCredentials = (typeof options.withCredentials !== 'undefined') ? options.withCredentials : false;
- var async = (typeof options.async !== 'undefined') ? options.async : true;
- var onError = (options.onError && typeof options.onError === 'function') ? options.onError : null;
- var onSuccess = (options.onSuccess && typeof options.onSuccess === 'function') ? options.onSuccess : null;
- var onTimeout = (options.onTimeout && typeof options.onTimeout === 'function') ? options.onTimeout : null;
- var _xhr = new XMLHttpRequest();
- _xhr.open(method, url, async, username, password);
- // can only set a timeout on asynchronous requests
- if(async) {
- _xhr.timeout = timeout;
- }
- if(withCredentials) {
- _xhr.withCredentials = withCredentials;
- }
- if(contentType) {
- _xhr.setRequestHeader('Content-Type', contentType);
- } else if(contentType !== false && method === 'POST') {
- _xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- }
- for (var key in headers) {
- _xhr.setRequestHeader(key, headers[key]);
- }
- _xhr.onreadystatechange = function() {
- if (this.readyState === 4) {
- if (this.status >= 200 && this.status < 400) {
- if(onSuccess) {
- onSuccess(this.responseText, this.status, this);
- }
- } else {
- if(onError) {
- onError(this, this.status);
- }
- }
- }
- };
- if(onTimeout) {
- _xhr.ontimeout = onTimeout;
- }
- _xhr.send(data);
- _xhr = null;
- }
- xhr({
- url: "http://foo.bar/customers"
- }
- xhr({
- url: "http://foo.bar/customers",
- method: "POST",
- data: 'foo=bar'
- }
- xhr({
- url: "http://foo.bar/customers",
- method: "POST",
- contentType: "application/json; charset=UTF-8"
- data: { foo: "bar" },
- onSuccess: function(response, statusCode, xhr) {
- }
- onError: function(xhr, statusCode) {
- },
- onTimeout: function(event) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement