首页 > 解决方案 > 如何使用 JQuery 从我的 JSON url 文件中检索两个值并应用于 Html?

问题描述

我是 jQuery 和 Json 的新手,我正在尝试做一个测验。

我现在的问题是从 Json url 文件中检索incorrect_answerscorrect_answer让它们显示为问题的答案选项。我现在被困住了,我对所有提示和答案都有帮助。

 **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);
             });
        }
    });
});

标签: jqueryjson

解决方案


看看这个片段。

// 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
  // (e.g. 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>

编辑

上面的代码片段必须修改为使用$.getJSON()而不是fetch()

我将两种解决方案都留在了片段中,但使用/工作的一个是$.getJSON()


推荐阅读