Just cant figure it out. I have a large object stored as a JSON file and I want to access it once and use it multiple times:
var myjson = new Object();
$.getJSON("myJSON.js", function(json) {
myjson = JSON.stringify(json);
});
$('#console').append(myjson);
This does nothing. It's a scope issue, I know. I just don't know how to do what I'm wanting. Must I do all my functions inside the $.getJSON call or is there a way to pass the object that I can use throughout runtime?
It's a scope issue, I know.
ReplyDeleteNo, it's not a scoping issue. It's an issue with your understanding about how AJAX works. AJAX is asynchronous. This means that when you send an AJAX request, the function that sent this request ($.getJSON in your case) returns immediately. It is only inside the success callback that you should use the results. This callback function could be called much later. It doesn't really depend on you at what moment in time in the future this might happen. Might never happen actually if there is an error on your server.
So the only place where you could reliably consume the results that the server sent after an AJAX call is inside the success callback:
$.getJSON("myJSON.js", function(json) {
// here and only here you can access the results of your AJAX call.
$('#console').append(JSON.stringify(json));
});
There are some horrible things that you could do like performing synchronous calls to the server:
var myjson = { };
$.ajax({
url: 'myJSON.js',
dataType: 'json',
async: false,
success: function(json) {
myjson = JSON.stringify(json);
}
});
$('#console').append(myjson);
The async: false option makes a synchronous call. Obviously this completely defeats the whole purpose of AJAX as it will freeze the browser during this call. You are probably better of directly including the myJSON.js as a script tag:
<script type="text/javascript" src="myJSON.js"></script>
Another benefit you might get from this approach is that the browser will ensure for you that this script is completely loaded before executing any other scripts. So the following could work fine:
<script type="text/javascript" src="myJSON.js"></script>
<script type="text/javascript">
var myjson = someJavascriptVariableThatYouDeclaredInMyJSON;
</script>
and then later:
<script type="text/javascript">
$('#console').append(JSON.stringify(myjson));
</script>