JavaScriptがブラウザに表示されるように、JSONファイルの情報が関数の完了後にロードされるという問題があります。私は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);
これは、ページロード時に呼び出す2つの関数にまとめられています。
window.onload = function() {
var quiz = new QuizBase('Knowledge', 'Product');
quiz.GetQuiz();
quiz.QuizSelection();
}
quiz.GetQuiz();
が完了した後、基本的にはquiz.QuizSelection();
を実行する方法が必要です。
ありがとうございます - 'getJSON()'のコールバックのどこにありますか?それは成功の部分ですか?だからJSONを手に入れたら? –
申し訳ありませんが、少し曖昧でした。まさにそれはコールバック関数でもあります。その中で、 'else'ブロック内の' if(err!= null) 'をチェックした後で、あなたの*コールバック関数をチェックして実行する場所です。 – Connum
大変感謝しています! :) –