我有一個問題,即在函數完成後,JSON文件中的信息正在加載,以便在JavaScript中將其顯示給瀏覽器。我一直在研究this stackoverflow post,它解釋瞭如何解決這個問題,但我無法解決如何在不使用JQuery的情況下做到這一點。我知道JQuesry會是更好的方式,但不幸的是我只能使用JavaScript。異步調用導致信息在加載之前顯示
首先我得到的JSON信息:
// Generic Function to get JSON data
this.getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
}
然後,我把它變成一個JavaScript對象:
this.GetQuiz = function() {
var thisQuiz = this;
// Get the extract the quiz from the JSON folder
app.getJSON('json/demo.json', function(err, data) {
if (err != null) { // If there's a problem
// Add a debug for getting the quiz JSON
console.log('Unable to load quiz: ' + err);
} else {
// Load the quiz into the quiz base
this.Title = data.title;
this.Introduction = data.longtitle;
this.HeroImage = imgBase + 'products/' + data.img;
this.About = data.extra;
// Set How To Play
if(this.Type == 'Knowledge') { // Knowledge Quiz
this.HowToPlayText = "Knowledge, how to play text...";
} else if (this.Type == 'Identity') { // Identity Quiz
this.HowToPlayText = "Identity, how to play text...";
} else if (this.Type == 'TrueFalse') { // TrueFalse Quiz
this.HowToPlayText = "True/false, how to play text...";
}
// Make sure we can see what we are loading if nothing displays
console.log('We are loading the quiz for the ' + this.Title + ' range');
// Load Questions
thisQuiz.GetQuestions();
}
}.bind(this));
}.bind(this);
然後我調用一個函數來顯示該對象的部分瀏覽器:
this.QuizSelection = function() {
// Fill the ID's with the right info
app.SetBackground('head', this.HeroImage);
console.log('1 ' + this.HeroImage);
app.LoadInnerHTML('breadcrumbs', 'Home/' + this.Title);
app.LoadInnerHTML('quizSelectionTitle',this.Title);
console.log('2 ' + this.Title);
app.LoadInnerHTML('quizSelectionIntro',this.Introduction);
console.log('3 ' + this.Introduction);
// Show the Quiz Selection and Heading
app.ShowSection('head');
app.ShowSection('quizSelection');
console.log('Quiz Selection');
}.bind(this);
這是所有包裝成兩個函數,我稱爲頁面加載:
window.onload = function() {
var quiz = new QuizBase('Knowledge', 'Product');
quiz.GetQuiz();
quiz.QuizSelection();
}
我在quiz.GetQuiz();
完成後基本上需要一種方法來運行quiz.QuizSelection();
。
謝謝 - getJSON()的回調函數裏面會是什麼?這是成功的一部分嗎?那麼如果它設法獲得JSON? –
對,對不起,這有點含糊。確切地說,這也是一個回調函數。在這裏面,在你檢查並執行你的*回調函數後,在'else'塊中檢查'if(err!= null)'。 – Connum
非常感謝! :) –