简体   繁体   English

如何使用JQuery从我的JSON网址文件中检索两个值并应用于HTML?

[英]How do I retrieve two values from my JSON url file with JQuery and apply on Html?

I'm new to jQuery and Json and I'm trying to make a quiz. 我是jQuery和Json的新手,正在尝试进行测验。

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. 我现在的问题是从Json url文件中检索incorrect_answers答案和incorrect_answers correct_answer ,并将它们显示为问题的答案选项。 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> 

EDIT 编辑

The snippet above had to be modified to use $.getJSON() instead of fetch() . 上面的代码段必须修改为使用$ .getJSON()而不是fetch()

I left both solutions in the snippet, but the used / working one is $.getJSON() . 我将两个解决方案都留在了代码段中,但是使用过的/有效的解决方案是$ .getJSON()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM