자바에서 퀴즈 퀴즈 웹 게임을 만들고 있습니다! 성공적으로 API에서 퀴즈 질문을 검색하고 있습니다. 어떻게 든 내 웹 페이지에서 API 응답의 질문을 채울 수 없습니다! 아래 코드 에서처럼 자기 선언 된 질문을 추가 할 수는 있지만!JSON에서 데이터 가져 오기 및 자바 스크립트로 채우기
이 quiz.js
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if(this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
question.js
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
는
function populate() {
if(quiz.isEnded()) {
showScores();
}
else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for(var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " +
quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
var 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.response);
}
};
xhr.send();
};
getJSON('https://opentdb.com/api.php?
amount=10&category=20&difficulty=medium&type=multiple',
function(err,data) {
alert('Your query count: ' + data.results[0].category);});
// create questions
var questions = [
new Question("Which one is not an object oriented programming language?",
["Java", "C#","C++", "C"], "C"),
new Question("Which language is used for styling web pages?", ["HTML",
"JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented
programming.", ["1", "6","2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python",
"Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"],
"Framework")];
var quiz = new Quiz(questions);
populate();
'populate' 함수는 어디에 있습니까? – Vivek
여기에 json 응답을 포함시킬 수 있습니까? – cdoshi
@Vivek 방금 ** app.js ** 코드를 추가했습니다! 친절 –