Possible Duplicate:
JavaScript asynchronous return value / assignment with jQuery
I need a prototype of chart with constructor, so I wrote this:
function Chart(file) {
var chart = undefined
$.getJSON(file, function(data) {
chart = {
categories: data.keys
series: [{
name: 'first',
data: data.first
}, {
name: 'second',
data: data.second
}]
}
});
return chart
}
Then I realized, that because of JaavScript’s synchronousness it returns undefined. How should I defere the return statement of Chart?
1.) Specify a callback function
2.) Synchronous request (not recommended!)
You could use
$.ajax()and set theasyncproperty tofalse.Warning: This method is not recommended! It blocks the whole UI, all other JavaScript and timers until the request is finished!