This question already has answers here:
</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call" dir="ltr">How do I return the response from an asynchronous call?</a>
<span class="question-originals-answer-count">
(38 answers)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2015-09-16 17:51:16Z" class="relativetime">4 years ago</span>.</div>
</div>
</aside>
How to get a data.json
{"key1":"val1","key2":"val2"}
with a function
var getJSON = function (url) {
var response = null;
return (function () {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
response = xhr.status == 200 ? xhr.response : xhr.status;
};
xhr.send();
})();
return response;
};
That the code
console.log(1);
console.log(getJSON('http://localhost/myproject/data.json'));
console.log(3);
gives
1
{"key1":"val1","key2":"val2"}
3
? Now it gives
1
null
3
Thank you
</div>