.then 在测验应用程序的获取功能中承诺的问题
Problem with .then promise in in the fetch function in the quiz app
我正在尝试学习本教程 -
https://www.youtube.com/watch?v=jK5zzSA2JHI
问题是,这部分代码对我不起作用 -
fetch("questions.json")
.then(res => {
return res.json();
})
.then(loadedQuestions => {
console.log(loadedQuestions);
questions = loadedQuestions;
startGame();
});
我一直在控制台中收到此错误 -
game.html:1 Uncaught (in promise) SyntaxError: Unexpected token } in JSON at position 244
我已经正确创建了 questions.json 文件,它位于我的项目文件夹中,看起来像这样 -
[
{
"question": "Inside which HTML element do we put the JavaScript??",
"choice1": "<script>",
"choice2": "<javascript>",
"choice3": "<js>",
"choice4": "<scripting>",
"answer": 1,
},
{
"question":
"What is the correct syntax for referring to an external script called 'xxx.js'?",
"choice1": "<script href='xxx.js'>",
"choice2": "<script name='xxx.js'>",
"choice3": "<script src='xxx.js'>",
"choice4": "<script file='xxx.js'>",
"answer": 3,
},
{
"question": " How do you write 'Hello World' in an alert box?",
"choice1": "msgBox('Hello World');",
"choice2": "alertBox('Hello World');",
"choice3": "msg('Hello World');",
"choice4": "alert('Hello World');",
"answer": 4,
},
]
这是本课完成的文件,由老师提供 -
https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/tree/master/10.%20Fetch%20Questions%20from%20Local%20JSON%20File
重要的文件可能是这个,因为问题可能出在这里 -
https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/blob/master/10.%20Fetch%20Questions%20from%20Local%20JSON%20File/game.js
在我应用获取代码之前一切正常,但现在当我尝试玩游戏时,问题甚至不会加载。
之前的解决方案是 game.js -
中的这段代码
let questions = [
{
question: "Inside which HTML element do we put the JavaScript??",
choice1: "<script>",
choice2: "<javascript>",
choice3: "<js>",
choice4: "<scripting>",
answer: 1
},
{
question:
"What is the correct syntax for referring to an external script called 'xxx.js'?",
choice1: "<script href='xxx.js'>",
choice2: "<script name='xxx.js'>",
choice3: "<script src='xxx.js'>",
choice4: "<script file='xxx.js'>",
answer: 3
},
{
question: " How do you write 'Hello World' in an alert box?",
choice1: "msgBox('Hello World');",
choice2: "alertBox('Hello World');",
choice3: "msg('Hello World');",
choice4: "alert('Hello World');",
answer: 4
}
];
- 这没问题,但现在我被这个 fetch and .then 代码困住了。谁能解释一下,这里可能出了什么问题?老实说,这 .then 让我有点困惑,我不太确定它的目的是什么,但我知道,这是某种承诺,但我希望能有一些万无一失的解释方式,当涉及到这个。
我自己的 game.js 文件目前看起来是这样的 -
//jshint esversion:6
const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const progressText = document.getElementById("progressText");
const scoreText = document.getElementById("score");
const progressBarFull = document.getElementById("progressBarFull");
//this is an object.
let currentQuestion = {};
// after someone answers, we will create a 1 second delay, before we let them answer again?
let acceptingAnswers = false;
// score will start at 0.
let score = 0;
//this is basically - what question are You on.
let questionCounter = 0;
//this is an array, which is going to be copy of our full question set
//and we are going to take questions out of the available questions array as we use them
//so that we can always find a unique question to give to user.
let avilableQuestions = [];
//questions - each question is going to be an object, answer: correct answer
//there is no zero based indexing in the answer field, it is starting at 1.
let questions = [];
fetch('questions.json')
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
console.log(loadedQuestions);
questions = loadedQuestions;
startGame();
});
//CONSTANTS
//when You get a answer corret, this is how much is it worth
const CORRECT_BONUS = 10;
//this is how many questions does a user get, before they finish.
const MAX_QUESTIONS = 3;
startGame = () => {
questionCounter = 0;
score = 0;
availableQuestions = [...questions];
getNewQuestion();
};
getNewQuestion = () => {
if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
localStorage.setItem("mostRecentScore", score);
//go to the end page
return window.location.assign("/end.html");
};
questionCounter++;
progressText.innerText = "Question " + questionCounter + "/" + MAX_QUESTIONS;
//the line above this line is an alternative to the line below this line.
// progressText.innerText = `Question ${questionCounter}/${MAX_QUESTIONS}`;
//Update the progress bar
progressBarFull.style.width = ((questionCounter / MAX_QUESTIONS) * 100) + "%";
//the line above this line is an alternative to the line below this line.
//progressBarFull.style.width = `${(questionCounter / MAX_QUESTIONS) * 100} px`;
const questionIndex = Math.floor(Math.random() * availableQuestions.length);
currentQuestion = availableQuestions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach(choice => {
const number = choice.dataset["number"];
choice.innerText = currentQuestion["choice" + number];
});
availableQuestions.splice(questionIndex, 1);
acceptingAnswers = true;
};
choices.forEach(choice => {
choice.addEventListener("click", e => {
if (!acceptingAnswers) return;
acceptingAnswers = false;
const selectedChoice = e.target;
const selectedAnswer = selectedChoice.dataset["number"];
// const classToApply = "incorrect";
// if(selectedAnswer == currentQuestion.answer) {
// classToApply = "correct";
// };
//tímto způsobem (říká se tomu ternary operator) se taky dá docílit toho, co dělá if statement nad tímto komentářem.
const classToApply =
selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";
if(classToApply === "correct") {
incrementScore(CORRECT_BONUS);
}
selectedChoice.parentElement.classList.add(classToApply);
setTimeout( () => {
selectedChoice.parentElement.classList.remove(classToApply);
getNewQuestion();
}, 1000);
//console.log(classToApply);
});
});
incrementScore = num => {
score += num;
scoreText.innerText = score;
};
谢谢你,祝你有愉快的一天。
如错误所示,您的 json 格式不正确。
不允许尾随逗号。
尝试用这个替换它。
[
{
"question": "Inside which HTML element do we put the JavaScript??",
"choice1": "<script>",
"choice2": "<javascript>",
"choice3": "<js>",
"choice4": "<scripting>",
"answer": 1
},
{
"question":
"What is the correct syntax for referring to an external script called 'xxx.js'?",
"choice1": "<script href='xxx.js'>",
"choice2": "<script name='xxx.js'>",
"choice3": "<script src='xxx.js'>",
"choice4": "<script file='xxx.js'>",
"answer": 3
},
{
"question": " How do you write 'Hello World' in an alert box?",
"choice1": "msgBox('Hello World');",
"choice2": "alertBox('Hello World');",
"choice3": "msg('Hello World');",
"choice4": "alert('Hello World');",
"answer": 4
}
]
我正在尝试学习本教程 - https://www.youtube.com/watch?v=jK5zzSA2JHI
问题是,这部分代码对我不起作用 -
fetch("questions.json")
.then(res => {
return res.json();
})
.then(loadedQuestions => {
console.log(loadedQuestions);
questions = loadedQuestions;
startGame();
});
我一直在控制台中收到此错误 -
game.html:1 Uncaught (in promise) SyntaxError: Unexpected token } in JSON at position 244
我已经正确创建了 questions.json 文件,它位于我的项目文件夹中,看起来像这样 -
[
{
"question": "Inside which HTML element do we put the JavaScript??",
"choice1": "<script>",
"choice2": "<javascript>",
"choice3": "<js>",
"choice4": "<scripting>",
"answer": 1,
},
{
"question":
"What is the correct syntax for referring to an external script called 'xxx.js'?",
"choice1": "<script href='xxx.js'>",
"choice2": "<script name='xxx.js'>",
"choice3": "<script src='xxx.js'>",
"choice4": "<script file='xxx.js'>",
"answer": 3,
},
{
"question": " How do you write 'Hello World' in an alert box?",
"choice1": "msgBox('Hello World');",
"choice2": "alertBox('Hello World');",
"choice3": "msg('Hello World');",
"choice4": "alert('Hello World');",
"answer": 4,
},
]
这是本课完成的文件,由老师提供 - https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/tree/master/10.%20Fetch%20Questions%20from%20Local%20JSON%20File
重要的文件可能是这个,因为问题可能出在这里 - https://github.com/jamesqquick/Build-A-Quiz-App-With-HTML-CSS-and-JavaScript/blob/master/10.%20Fetch%20Questions%20from%20Local%20JSON%20File/game.js
在我应用获取代码之前一切正常,但现在当我尝试玩游戏时,问题甚至不会加载。 之前的解决方案是 game.js -
中的这段代码let questions = [
{
question: "Inside which HTML element do we put the JavaScript??",
choice1: "<script>",
choice2: "<javascript>",
choice3: "<js>",
choice4: "<scripting>",
answer: 1
},
{
question:
"What is the correct syntax for referring to an external script called 'xxx.js'?",
choice1: "<script href='xxx.js'>",
choice2: "<script name='xxx.js'>",
choice3: "<script src='xxx.js'>",
choice4: "<script file='xxx.js'>",
answer: 3
},
{
question: " How do you write 'Hello World' in an alert box?",
choice1: "msgBox('Hello World');",
choice2: "alertBox('Hello World');",
choice3: "msg('Hello World');",
choice4: "alert('Hello World');",
answer: 4
}
];
- 这没问题,但现在我被这个 fetch and .then 代码困住了。谁能解释一下,这里可能出了什么问题?老实说,这 .then 让我有点困惑,我不太确定它的目的是什么,但我知道,这是某种承诺,但我希望能有一些万无一失的解释方式,当涉及到这个。
我自己的 game.js 文件目前看起来是这样的 -
//jshint esversion:6
const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const progressText = document.getElementById("progressText");
const scoreText = document.getElementById("score");
const progressBarFull = document.getElementById("progressBarFull");
//this is an object.
let currentQuestion = {};
// after someone answers, we will create a 1 second delay, before we let them answer again?
let acceptingAnswers = false;
// score will start at 0.
let score = 0;
//this is basically - what question are You on.
let questionCounter = 0;
//this is an array, which is going to be copy of our full question set
//and we are going to take questions out of the available questions array as we use them
//so that we can always find a unique question to give to user.
let avilableQuestions = [];
//questions - each question is going to be an object, answer: correct answer
//there is no zero based indexing in the answer field, it is starting at 1.
let questions = [];
fetch('questions.json')
.then((res) => {
return res.json();
})
.then((loadedQuestions) => {
console.log(loadedQuestions);
questions = loadedQuestions;
startGame();
});
//CONSTANTS
//when You get a answer corret, this is how much is it worth
const CORRECT_BONUS = 10;
//this is how many questions does a user get, before they finish.
const MAX_QUESTIONS = 3;
startGame = () => {
questionCounter = 0;
score = 0;
availableQuestions = [...questions];
getNewQuestion();
};
getNewQuestion = () => {
if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
localStorage.setItem("mostRecentScore", score);
//go to the end page
return window.location.assign("/end.html");
};
questionCounter++;
progressText.innerText = "Question " + questionCounter + "/" + MAX_QUESTIONS;
//the line above this line is an alternative to the line below this line.
// progressText.innerText = `Question ${questionCounter}/${MAX_QUESTIONS}`;
//Update the progress bar
progressBarFull.style.width = ((questionCounter / MAX_QUESTIONS) * 100) + "%";
//the line above this line is an alternative to the line below this line.
//progressBarFull.style.width = `${(questionCounter / MAX_QUESTIONS) * 100} px`;
const questionIndex = Math.floor(Math.random() * availableQuestions.length);
currentQuestion = availableQuestions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach(choice => {
const number = choice.dataset["number"];
choice.innerText = currentQuestion["choice" + number];
});
availableQuestions.splice(questionIndex, 1);
acceptingAnswers = true;
};
choices.forEach(choice => {
choice.addEventListener("click", e => {
if (!acceptingAnswers) return;
acceptingAnswers = false;
const selectedChoice = e.target;
const selectedAnswer = selectedChoice.dataset["number"];
// const classToApply = "incorrect";
// if(selectedAnswer == currentQuestion.answer) {
// classToApply = "correct";
// };
//tímto způsobem (říká se tomu ternary operator) se taky dá docílit toho, co dělá if statement nad tímto komentářem.
const classToApply =
selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";
if(classToApply === "correct") {
incrementScore(CORRECT_BONUS);
}
selectedChoice.parentElement.classList.add(classToApply);
setTimeout( () => {
selectedChoice.parentElement.classList.remove(classToApply);
getNewQuestion();
}, 1000);
//console.log(classToApply);
});
});
incrementScore = num => {
score += num;
scoreText.innerText = score;
};
谢谢你,祝你有愉快的一天。
如错误所示,您的 json 格式不正确。
不允许尾随逗号。
尝试用这个替换它。
[
{
"question": "Inside which HTML element do we put the JavaScript??",
"choice1": "<script>",
"choice2": "<javascript>",
"choice3": "<js>",
"choice4": "<scripting>",
"answer": 1
},
{
"question":
"What is the correct syntax for referring to an external script called 'xxx.js'?",
"choice1": "<script href='xxx.js'>",
"choice2": "<script name='xxx.js'>",
"choice3": "<script src='xxx.js'>",
"choice4": "<script file='xxx.js'>",
"answer": 3
},
{
"question": " How do you write 'Hello World' in an alert box?",
"choice1": "msgBox('Hello World');",
"choice2": "alertBox('Hello World');",
"choice3": "msg('Hello World');",
"choice4": "alert('Hello World');",
"answer": 4
}
]