Last active
October 13, 2015 06:08
-
-
Save calvinte/4151151 to your computer and use it in GitHub Desktop.
500px api connection
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
/** | |
* Function generates parts of URI paramaters. | |
* @param param_name as String. | |
* @param root as String representing the root paramater in an array. | |
*/ | |
encodeParamName = function(param_name, root) { | |
if (root) return encodeURIComponent(root + '[' + param_name + ']'); | |
else return encodeURIComponent(param_name); | |
}; | |
/** | |
* Function takes object and returns it's parts as a string of paramaters | |
* for use in a URI. | |
* @param object as Object. | |
* @param use as String (used for recursion). | |
* @return String as paramaters for URI. | |
*/ | |
objectToParams = function(object, root) { | |
var string_parts = []; | |
// Loop through object, extract all properties and append them | |
// to the string_parts array. | |
for (var property in object) { | |
if (object.hasOwnProperty(property)) { | |
var value = object[property]; | |
if (value instanceof Array) { | |
// Property is an array. | |
for (var i = 0; i < value.length; i++) { | |
var encoded_value = encodeURIComponent(value[i]), | |
param_name = this.encodeParamName(property, root); | |
string_parts.push(param_name + '%5B%5D=' + encoded_value); | |
} | |
} else if (typeof value == 'object') { | |
// Property is an object. | |
var param_name = this.encodeParamName(property, root); | |
string_parts.push(objectToParams(value, param_name)); | |
} else { | |
// Property is a string. | |
var param_name = this.encodeParamName(property, root), | |
URIComponent = encodeURIComponent(value); | |
string_parts.push(param_name + '=' + URIComponent); | |
} | |
} | |
} | |
// Join our parts and return the string. | |
return string_parts.join('&'); | |
}; | |
var params = { | |
feature: 'popular', | |
image_size: 4, | |
consumer_key: 'EX4MPL3C0NSUM3RK3Y', | |
callback: 'callback', | |
}; | |
var url = 'https://api.500px.com/v1/' + 'photos.jsonp' + '?' + objectToParams(params); | |
// Construct JSONP request | |
tag = document.createElement('script'); | |
tag.src = url; | |
document.body.appendChild(tag); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment