JSON file content assignment to global variable
Hi jQuery Forum Users,
I encountered a problem, when trying to assign a json file content to a global variable. A short explanation - There is a file called test.json with some json content, which shall be assigned to a global variable using jQuery. For this purpose, I am using XMLHttpRequest. A defined function loadJSON calls XMLHttpRequest, with a callback function handling the json file content after a successful request. But the json file content is only available within the callback function or rather in the defined function inside loadJSON.
I wanna load also other json file contents, but how is possible to access them outside the loadJSON function, especially in the function block of the $( document ).ready event handler?
How is possible to achieve it or isn't this possible at all, what i do imagine?
I would appreciate any answer.
with best regards, NewJQ.
- <html>
<head>
<script src="jquery.js"></script>
<script>
$( document ).ready(
function() {
var data = null;
loadJSON(
'http://localhost/json/test.json',
function( response ) {
var data = JSON.parse( response );
console.log( data ); // is accessable
}
);
// is not accessable
// but data, as well as data2, ... (future variables) are needed for
// other functions and should be accessable here
}
);
function loadJSON ( url, callback ) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', url, true);
request.onreadystatechange = function () {
if ( request.readyState == 4 && request.status == "200" ) {
var data = callback ( request.responseText ); // is accessable
}
};
request.send();
}
</script>
</head>
<body>
</body>
</html>