Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple JavaScript HTTP Client. Supports GET and POST.
httpClient = {
get: function( url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString = '';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
}
if (queryString.length !== 0) {
url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
}
xhr.open('GET', url, true);
xhr.send(null);
},
post: function( url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString = '';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
}
xhr.open('POST', url, true);
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
xhr.send(queryString);
}
};
// Get all gists for user 'randyburden' and output the Url and Description of each gist to the JavaScript console
httpClient.get( 'https://api.github.com/users/randyburden/gists', null, function(xhr) {
//console.log( JSON.parse( xhr.responseText ) );
var gists = JSON.parse( xhr.responseText );
var list = [];
for( var i = 0; i < gists.length; i++ ) {
list.push( { Url: gists[i].html_url, Description: gists[i].description } );
}
console.log( list );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment