D
D
dogmator2017-02-07 12:42:13
JavaScript
dogmator, 2017-02-07 12:42:13

How to get JSON and put it into external variable?

var JSONexternal = getJSON('/php/vesettingsforclient.php', function(response) {
    return JSON.parse(response);
});
console.log(JSONexternal); // undefined

function getJSON(url, callback) {
    var xhr = new getXmlHttpInstance();
    xhr.open("GET", url, true);
    xhr.send();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            if (typeof callback === 'function') {
                callback.call(this, this.responseText); // как отсюда вытащить ответ во внешний скрипт?
            }
        }
    };
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Borovik, 2017-02-07
@borovik_96

Because the getJSON function does not return anything, you get the value through a callback, in order for your code to work, you need to do this:

var JSONexternal = getJSON('/php/vesettingsforclient.php', function(response) {

   // response доступен только тут, эта функция вызывется асинхронно 
    console.log( JSON.parse(response));
});

function getJSON(url, callback) {
    var xhr = new getXmlHttpInstance();
    xhr.open("GET", url, true);
    xhr.send();
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            if (typeof callback === 'function') {
                callback.call(this, this.responseText); // как отсюда вытащить ответ во внешний скрипт?
            }
        }
    };
}

I
Ivan Sushkov, 2017-02-07
@jamesgoodwin

Is it possible that your callback expects one "response" and you give it two parameters? Try something like this:
I recommend logging to find out what is the reason. This is actually faster and more productive. There isn't much code. It is interesting what is returned in the response to the request and what is passed to your callback.
PS Do you have this.readyState, this.status and this.responseText working at all? Usually xhr.readyState, xhr.status and xhr.responseText.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question