0

I have a myurl.txt e.g containing

{'name':'myname','age':23}

How to do a function

function getRequest() {
    var result = {};
    (function() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            result = JSON.parse(xmlhttp.responseText);
        };
        xmlhttp.open("GET", "myurl.txt", true);
        xmlhttp.send();
    })();
    return result;
}
console.log(1);
console.log(getRequest());
console.log(2);

that i can get the result, that it do the function onreadystatechange as the last thing (without a jQuery). And write to a console

1
{'name':'myname','age':23}
2

Thank you.

user2301515
  • 4,903
  • 6
  • 30
  • 46
  • The linked duplicate explains how asynchronous operations work, how to use a value fetched inside a function, and (therefore) how to correctly structure your code to make it run in the order you want. – apsillers Dec 02 '14 at 16:44
  • I'm pushing back allegations of duplication. I composed the question by hand. I'm searching a solution WITHOUT jQuery. – user2301515 Dec 02 '14 at 16:56
  • Of course -- no one is suggesting you plagiarized the linked question. In fact, the assumption is usually that you have never *seen* the original (because if you had, your question would be answered already.) Marking duplicates is intended to concentrate useful information into central hubs, rather than leave it scattered across multiple similar questions. Marking your question as a duplicate is not any kind of accusation; it is an organizational tool. – apsillers Dec 02 '14 at 17:00
  • The problem is not unique to jQuery, but if you prefer to see an explanation that does not use jQuery code, see [the second answer](http://stackoverflow.com/a/16825593/710446). – apsillers Dec 02 '14 at 17:05

0 Answers0