Skip to content

Instantly share code, notes, and snippets.

@randyburden
Created May 11, 2015 03:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save randyburden/67f7c208772f9a4768e6 to your computer and use it in GitHub Desktop.
Save randyburden/67f7c208772f9a4768e6 to your computer and use it in GitHub Desktop.
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