var notes = [];
$(document).ready(function() {
//var notes = [];
alert("before " + notes.length);
init();
alert("after " + notes.length)
//execute(notes, 0);
});
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
var len = actual_JSON.notes.length;
//alert("length is " + len);
for(var i = 0; i < 6; i++) {
notes.push(actual_JSON.notes[i]);
}
//alert("after for loop " + notes.length);
});
}
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'test.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
答案 0 :(得分:0)
使用承诺
var notes = [];
$(document).ready(function() {
alert("before " + notes.length);
init()
.then(function(){
alert("after " + notes.length)
})
.catch(function(err){
console.log('error in init()', err)
});
});
function init() {
return new Promise(function(resolve, reject) {
loadJSON(function(response) {
var actual_JSON = JSON.parse(response);
var len = actual_JSON.notes.length;
for(var i = 0; i < 6; i++) {
notes.push(actual_JSON.notes[i]);
}
resolve()
});
});
}
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'test.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);