如何使用外部json文件进行测验

时间:2018-11-21 00:12:33

标签: javascript json

所以正如标题所说。如何将外部json文件用于测验数据,而不是在JavaScript代码中使用数组。因此,使用var Questions数组并将其放入一个单独的json文件中,然后将其调用到javascript中使用,所有单选按钮都代表选择。我不确定该怎么做

<!DOCTYPE html>
<html>

<head>
    <title> aa</title>
    <link rel="stylesheet" href="styles.css">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
    <header id="main-header">
        <h1>
            <center> quiz </center>
        </h1>
    </header>
    <div id='container'>
        <div id='title'>
            <h1>Learning Js Properly: Project #1 - Dynamic Quiz</h1>
        </div>
        <br />
        <div id='quiz'></div>
        <div class='button' id='next'><a href=''>Next</a></div>
        <div class='button' id='prev'><a href='#'>Prev</a></div>
        <div class='button' id='start'> <a href='#'>Start Over</a></div>
        <!-- <button class='' id='next'>Next</a></button>
      		<button class='' id='prev'>Prev</a></button>
      		<button class='' id='start'> Start Over</a></button> -->
    </div>

    <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
    <script type="text/javascript" src='questions.json'></script>
    <script type='text/javascript' src='jsquiz.js'></script>

    <script>
        (function() {
            var questions = [{
                question: "What is 2*5?",
                choices: [2, 5, 10, 15, 20],
                correctAnswer: 2
            }, {
                question: "What is 3*6?",
                choices: [3, 6, 9, 12, 18],
                correctAnswer: 4
            }, {
                question: "What is 8*9?",
                choices: [72, 99, 108, 134, 156],
                correctAnswer: 0
            }, {
                question: "What is 1*7?",
                choices: [4, 5, 6, 7, 8],
                correctAnswer: 3
            }, {
                question: "What is 8*8?",
                choices: [20, 30, 40, 50, 64],
                correctAnswer: 4
            }];

            var questionCounter = 0; //Tracks question number
            var selections = []; //Array containing user choices
            var quiz = $('#quiz'); //Quiz div object

            // Display initial question
            displayNext();

            // Click handler for the 'next' button
            $('#next').on('click', function(e) {
                e.preventDefault();

                // Suspend click listener during fade animation
                if (quiz.is(':animated')) {
                    return false;
                }
                choose();

                // If no user selection, progress is stopped
                if (isNaN(selections[questionCounter])) {
                    alert('Please make a selection!');
                } else {
                    questionCounter++;
                    displayNext();
                }
            });

            // Click handler for the 'prev' button
            $('#prev').on('click', function(e) {
                e.preventDefault();

                if (quiz.is(':animated')) {
                    return false;
                }
                choose();
                questionCounter--;
                displayNext();
            });

            // Click handler for the 'Start Over' button
            $('#start').on('click', function(e) {
                e.preventDefault();

                if (quiz.is(':animated')) {
                    return false;
                }
                questionCounter = 0;
                selections = [];
                displayNext();
                $('#start').hide();
            });

            // Animates buttons on hover
            $('.button').on('mouseenter', function() {
                $(this).addClass('active');
            });
            $('.button').on('mouseleave', function() {
                $(this).removeClass('active');
            });

            // Creates and returns the div that contains the questions and
            // the answer selections
            function createQuestionElement(index) {
                var qElement = $('<div>', {
                    id: 'question'
                });

                var header = $('<h2>Question ' + (index + 1) + ':</h2>');
                qElement.append(header);

                var question = $('<p>').append(questions[index].question);
                qElement.append(question);

                var radioButtons = createRadios(index);
                qElement.append(radioButtons);

                return qElement;
            }

            // Creates a list of the answer choices as radio inputs
            function createRadios(index) {
                var radioList = $('<ul>');
                var item;
                var input = '';
                for (var i = 0; i < questions[index].choices.length; i++) {
                    item = $('<li>');
                    input = '<input type="radio" name="answer" value=' + i + ' />';
                    input += questions[index].choices[i];
                    item.append(input);
                    radioList.append(item);
                }
                return radioList;
            }

            // Reads the user selection and pushes the value to an array
            function choose() {
                selections[questionCounter] = +$('input[name="answer"]:checked').val();
            }

            // Displays next requested element
            function displayNext() {
                quiz.fadeOut(function() {
                    $('#question').remove();

                    if (questionCounter < questions.length) {
                        var nextQuestion = createQuestionElement(questionCounter);
                        quiz.append(nextQuestion).fadeIn();
                        if (!(isNaN(selections[questionCounter]))) {
                            $('input[value=' + selections[questionCounter] + ']').prop('checked', true);
                        }

                        // Controls display of 'prev' button
                        if (questionCounter === 1) {
                            $('#prev').show();
                        } else if (questionCounter === 0) {

                            $('#prev').hide();
                            $('#next').show();
                        }
                    } else {
                        var scoreElem = displayScore();
                        quiz.append(scoreElem).fadeIn();
                        $('#next').hide();
                        $('#prev').hide();
                        $('#start').show();
                    }
                });
            }

            // Computes score and returns a paragraph element to be displayed
            function displayScore() {
                var score = $('<p>', {
                    id: 'question'
                });

                var numCorrect = 0;
                for (var i = 0; i < selections.length; i++) {
                    if (selections[i] === questions[i].correctAnswer) {
                        numCorrect++;
                    }
                }

                score.append('You got ' + numCorrect + ' questions out of ' +
                    questions.length + ' right!!!');
                return score;
            }
        })();
    </script>



</body>

</html>

2 个答案:

答案 0 :(得分:0)

您可以简单地通过以下方式fetch JSON:

fetch(url)
  .then(result => JSON.parse(result))
  .then(resultParsed => {
    //do something with result after parsing
    console.log(resultParsed)
  })

另请参阅:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

答案 1 :(得分:-1)

就像将您的问题数组放入一个名为questions.js的文件那样简单,就像这样:

questions = [
  {
    question: "What is 2*5?",
    choices: [2, 5, 10, 15, 20],
    correctAnswer: 2
  },
  {
    question: "What is 3*6?",
    choices: [3, 6, 9, 12, 18],
    correctAnswer: 4
  },
  {
    question: "What is 8*9?",
    choices: [72, 99, 108, 134, 156],
    correctAnswer: 0
  },
  {
    question: "What is 1*7?",
    choices: [4, 5, 6, 7, 8],
    correctAnswer: 3
  },
  {
    question: "What is 8*8?",
    choices: [20, 30, 40, 50, 64],
    correctAnswer: 4
  }
];

然后在您的身体底部贴上标签<script src="questions.js" type="text/javascript"></script>

然后,当您第一次需要数组时,只需将其称为问题即可(无需使用var或let声明它)。