首页 > 解决方案 > 测验应用程序的 fetch 函数中的 .then 承诺问题

问题描述

我正在尝试遵循本教程 - 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 %20问题%20来自%20Local%20JSON%20文件

重要的文件可能是这个,因为问题可能就在那里 - 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
  }
];

到目前为止,我自己的 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;
};

谢谢你,祝你有美好的一天。

标签: javascriptconsolefetchconsole.log

解决方案


正如错误所示,您的 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
    }
]

推荐阅读