Java Reference
In-Depth Information
Quiz Ninja Project
We can use Ajax to fetch the questions from a server, instead of keeping them in an object
inside our JavaScript file. First of all, we remove the object stored in the quiz variable at
the start of the scripts.js file and transfer the information into a separate file. This informa-
tion has to be in the JSON format, so the properties need to be strings. The file is saved on
SitePoint's S3 account and can be found at the following URL (it also contains lots more
questions than the three we've been using so far):
To access this JSON data, we need a function that will create an Ajax request to fetch the
data. Add the following function just after the "use strict" line in the scripts.js file:
// gets the question JSON file using Ajax
function getQuiz() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status == 200) {
var quiz = JSON.parse(xhr.responseText);
new Game(quiz);
};"GET", "
jsninja/quiz.json", true);
update($question, "Waiting for questions...");
This function creates a new XMLHttpRequest object and then uses the JSON.parse()
method to convert the JSON data in the response into a native JavaScript object. This object
is then given as an argument to the Game() constructor function that we created in the last
chapter to launch the game. After this, we use the open() method to request the data, the
Search WWH ::

Custom Search