Last active
December 3, 2015 00:44
-
-
Save brunomrpx/e4b030cc2b35319786a4 to your computer and use it in GitHub Desktop.
Simple object to make Ajax requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var ajax = (function() { | |
'use strict'; | |
var xmlHttpRequest; | |
var states = { | |
UNSET: 0, | |
OPENED: 1, | |
HEADERS_RECEIVED: 2, | |
LOADING: 3, | |
DONE: 4 | |
}; | |
var defaultHeaders = [ | |
{ | |
'Content-Type': 'application/x-www-form-urlencoded' | |
} | |
]; | |
function send(url, options) { | |
xmlHttpRequest = new XMLHttpRequest(); | |
options.method = options.method || ''; | |
options.data = options.data || ''; | |
xmlHttpRequest.addEventListener('readystatechange', function() { | |
if (this.readyState == states.DONE) { | |
if (options.callback && typeof options.callback == 'function') { | |
options.callback(xmlHttpRequest); | |
} | |
} | |
}); | |
xmlHttpRequest.open(options.method, url); | |
configure(options.configuration || {}); | |
xmlHttpRequest.send(options.data || null); | |
} | |
function addHeaders(headersList) { | |
var headerItem, | |
index, | |
headerValue, | |
headerName; | |
for (index in headersList) { | |
headerItem = headersList[index]; | |
for (headerName in headerItem) { | |
headerValue = headerItem[headerName]; | |
xmlHttpRequest.setRequestHeader(headerName, headerValue); | |
} | |
} | |
} | |
function configure(configuration) { | |
var headersList = configuration.headers || defaultHeaders; | |
addHeaders(headersList); | |
xmlHttpRequest.timeout = configuration.timeout || 0; | |
xmlHttpRequest.responseType = configuration.responseType || ""; | |
} | |
return { | |
send: send | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment