P
P
pandaa2020-04-14 16:29:50
JavaScript
pandaa, 2020-04-14 16:29:50

How to return value to parent function?

function getFile(url) { 
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                return xhr.responseText;
            }
        }

        xhr.open('GET', url);
        xhr.send();
    }

function somefunc() { 
    return getFile('http://domain/n.php'); 
}

console.log(somefunc())  //undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mrspd, 2020-04-14
@mrspd

function getFile(url, cb) { 
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (typeof cb === 'function') { 
                        cb(xhr.responseText); 
                }
            }
        }

        xhr.open('GET', url);
        xhr.send();
    }

    return getFile('http://domain/n.php', function (data) { console.log(data);  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question