How to load the initial data before the rest of the javascript code runs?
I cant figure out how to load from the server the essential initial data that is used by the rest of my javascript code after $(document).ready(function(){
.
In concrete terms:
In index.html
I have
<head>
<script type="text/javascript" src="js/data.js"></script>
...
$(document).ready(function(){
initialize();
console.log(grantsData);
...
This returns to the Firebug console "grantsData is undefined"
In the file data.js
I have
var grantsData;
$.getJSON( "js/mysql_query_grants2.php", function(json){
alert("got SQL data as json");
grantsData = json;
console.log(grantsData);
}
this returns to the console what is expected.
Questions:
Does this infer that .getJSON() did not get a chance to finish returning the grantsData result before the code ran in index.html
?
How can I change so my key initial grantsData is all loaded, after initialize()
, BUT before any other javascript that depends on this data in run?
What is the alternative non-AJAX to getJSON()开发者_JS百科?
Stay asynchronous.
$(document).ready(function(){
// 1
initialize_everything(function() {
// 6
console.log(grantsData);
...
});
// 4
}
In data.js
:
function initialize_everything(callback) {
// 2
$.getJSON( "js/mysql_query_grants2.php", function(json){
// 5
// ...
// NOW we have everything, so report back
callback();
}
}
// 3
}
Does this infer that .getJSON() did not get a chance to finish returning the grantsData result before the code ran in index.html?
It's asynchronous, it processes its data (i.e. runs the code that is passed to it) as soon as the server's response arrives. In the meantime, your browser continues to execute the JavaScript, so the $(document).ready()
callback is invoked even though that other, unrelated AJAX request may not have completed yet. If you rely on a certain timing of your callbacks, your app might behave differently in different browsers or fail randomly.
The heavy use of closures (i.e. local function() {}
s which are passed around and invoked later) is JavaScript's idiomatic way to deal with asynchronous program flow.
Edit: to clarify this, I added a possible execution order to the above sample.
If you don't want direct dependency with functions, you can use custom events for your gransdata object and trigger other things when its changed or filled.
here is a nice link on that.
精彩评论