-
-
Save Humberfrench/8835a21e946fb79985cc1a3941c02c71 to your computer and use it in GitHub Desktop.
Simple JavaScript HTTP Client. Supports GET and POST.
This file contains 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
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); | |
} | |
}; |
This file contains 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
// 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