Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
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.")}
)
It can be even simpler, everything works. But! I can't pull out a local variable with the result from the function and make it global. Please tell me, is it possible to write this one here - result.response[0]['first_name'], somehow write it to a global variable, I've already tried everything (
var api= "https://api.vk.com/method/users.get?user_id=1&v=5.45&callback=callbackFunc";
var script= document.createElement('SCRIPT');
script.src= api;
document.getElementsByTagName("head")[0].appendChild(script);
function callbackFunc(result) {
alert(result.response[0]['first_name']);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question