is = {
type: function (value, type) {return {}.toString.call(value).match(/ ([a-z]+)/i)[1] == type}
}
registry = {}
function API_request(method, parameters, success, error) {
if (!is.type(parameters, "Object")) {
console.error("parameters must be an object.")
return
}
var callback = "c" + String(Math.random()).slice(-6)
var flag = false
registry[callback] =
function (data) {
flag = true
delete registry[callback]
if (is.type(success, "Function")) {success(data)}
}
var URL = "https://api.vk.com/method/" + method + "?"
for (var key in parameters) {URL += key + "=" + parameters[key] + "&"}
var script = document.createElement("script")
script.src = URL + "callback=registry." + callback
script.onload = script.onerror =
function () {
if (flag) {return}
delete registry[callback]
if (is.type(error, "Function")) {error()}
}
document.head.appendChild(script)
}
API_request(
"users.get",
{
user_ids: "1,2,3",
fields: "photo_50"
},
function (response) {
for (i = 0; i < response.response.length; i++) {
img = document.createElement("img")
img.src = response.response[i].photo_50
document.body.appendChild(img)
}
},
function () {alert("An error occured. No data loaded.")}
)