Reputation: 690
I am making a trivia game with JSON, and I am stuck. First off, I can pull my data from JSON and get it to display in a list after working through the documentation, like so:
$.getJSON('/trivia.json', function(data) {
var items = []
$.each(data, function (item, i) {
items.push('<li id="' + i.order + '">' + i.question + ' - ' + i.choices + i.correct + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('#example');
});
That works fine at creating a list of the questions and answers, so I can confirm I am calling the local JSON file correctly.
My next step is to get the question and answer data to be stored in my Javascript variable for the quiz to wrok. When I made the example quiz, I store the data like so:
var quiz = [
{
"question" : "Q1: Who came up with the theory of relativity?",
"choices" : [
"Sir Isaac Newton",
"Nicolaus Copernicus",
"Albert Einstein",
"Ralph Waldo Emmerson"
],
"correct" : "Albert Einstein",
}];
I don't want the questions to be static, so I want JSON to take over supplying the question and choices.
I have tried to call the appendTo function for the quiz var, but it isn't passing the data through like it was when I created a list. Any ideas on how I can get the question, choices, and correct data sets to apply with the var quiz?
Upvotes: 1
Views: 121
Reputation: 9808
You may update your code to add the grapped data from Ajax request to quiz variable and iterate over choices to print them like the following code:
var quiz = [
{
"question" : "Q1: Who came up with the theory of relativity?",
"choices" : [
"Sir Isaac Newton",
"Nicolaus Copernicus",
"Albert Einstein",
"Ralph Waldo Emmerson"
],
"correct" : "Albert Einstein",
}];
$.getJSON('/trivia.json', function(data) {
var items = []
$.each(data, function (item, i) {
var q = {"question": i.question, "correct": i.correct, "choices": []};
var choicesStr = "";
$.each(i.choices, function (it, choice) {
choicesStr += "<span>choice</span></br>";
q.choices.push(choice);
}
quiz.push(q);
items.push('<li id="' + i.order + '">' + i.question + ' - ' + choicesStr + i.correct + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('#example');
});
Upvotes: 1