I'm new to jQuery and Json and I'm trying to make a quiz.
My problem right now is to retrieve incorrect_answers
and correct_answer
from Json url file and have them display as answer options for the questions. I'm stuck right now and I'm helpful for all the tips and answers.
**Json**
{
"response_code": 0,
"results": [
{
"category": "History",
"type": "multiple",
"difficulty": "medium",
"question": "What disease crippled President Franklin D. Roosevelt and led him to help the nation find a cure? ",
"correct_answer": "Polio",
"incorrect_answers": [
"Cancer",
"Meningitis",
"HIV"
]
},
{
"category": "Science: Computers",
"type": "multiple",
"difficulty": "easy",
"question": "What does the Prt Sc button do?",
"correct_answer": "Captures what's on the screen and copies it to your clipboard",
"incorrect_answers": [
"Nothing",
"Saves a .png file of what's on the screen in your screenshots folder in photos",
"Closes all windows"
]
},
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "medium",
"question": "Which puzzle game was designed by a Russian programmer, featuring Russian buildings and music?",
"correct_answer": "Tetris",
"incorrect_answers": [
"Jenga",
"Boulder Dash",
"Puzzled"
]
},
{
"category": "Geography",
"type": "multiple",
"difficulty": "hard",
"question": "Where is the fast food chain "Panda Express" headquartered?",
"correct_answer": "Rosemead, California",
"incorrect_answers": [
"Sacremento, California",
"Fresno, California",
"San Diego, California"
]
},
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "easy",
"question": "In what year was Hearthstone released?",
"correct_answer": "2014",
"incorrect_answers": [
"2011",
"2013",
"2012"
]
}
**Html**
<h2>History Quiz</h2>
<a href="#">Start the Quiz</a>
<h2>Question:</h2>
<ul>
<li></li>
</ul>
<a href="#">Submit</a>
<div id="next-question"></div>
**jQuery**
$(function () {
var start = $('.start');
var quiz = $('.quiz');
var questionIndex = 0;
var questionData = [];
start.on('click', function() {
start.hide();
quiz.show();
seeQuestion();
createRadioButton();
});
function seeQuestion() {
var questions = questionData[questionIndex];
$('.quiz h2').text(questions.question);//question is viewed in h2
console.log(questions);
$('.quiz ul').html(' ');
//code for the answers
};
// create buttons
function createRadioButton() {
for (i = 0; i < 5; i++) {
$('<input type="radio" name="dynradio" />').appendTo('.quiz ul ');
};
};
$.ajax({
url: 'https://api.myjson.com/bins/9ocrl',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.results).each(function(key, value) {
questionData.push(value);
});
}
});
});
Have a look at this snippet.
// data variable that will be "filled" when the // API request resolves with data let data // containers and "active" parts const question = document.getElementById('question'); const answers = document.getElementById('answers'); const btnNext = document.getElementById('next'); // self calling async function (async function() { // fetching data from the API and waiting for the // returned Promise to resolve (or reject) // data = await getDataFromAPI() // with $.getJSON() data = await getJSONData() console.log('data', data) // activating the next button that is disabled // on initial load btnNext.removeAttribute('disabled') })(); // actual function to get data from API function getDataFromAPI() { return new Promise((resolve, reject) => { fetch('https://api.myjson.com/bins/9ocrl') .then(r => r.json()) .then(r => resolve(r)) .catch(err => reject(err)) }) } // using $.getJSON() to retrieve data from the API endpoint function getJSONData() { return new Promise((resolve, reject) => { jQuery.getJSON('https://api.myjson.com/bins/9ocrl', function(response) { resolve(response) }) }) } // counter - to keep track of current question var currentQuestionId = 0 // next question code btnNext.addEventListener('click', function(e) { if (data.results.length > currentQuestionId) { displayQuestion(currentQuestionId) currentQuestionId++ } else { displayFinish() currentQuestionId = 0 } }) function displayQuestion(questionId) { question.textContent = data.results[currentQuestionId].question // you can define the answer templates here // (eg add radiobuttons or something) let html = '' createAnswers(currentQuestionId).forEach((e, i) => { html += `<li>Answer ${i}: ${e}</li>` }) answers.innerHTML = html } function displayFinish() { answers.innerHTML = '' question.textContent = 'You\\'ve finished the quiz!' } // creating the array for the answers function createAnswers(questionId) { // you can randomize the answer order here (for example) return [data.results[questionId].correct_answer, ...data.results[questionId].incorrect_answers] }
.disabled {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="next" disabled>NEXT</button> <div id="question"></div> <ul id="answers"> </ul>
The snippet above had to be modified to use $.getJSON() instead of fetch() .
I left both solutions in the snippet, but the used / working one is $.getJSON() .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.