首页 > 解决方案 > 简单的 ajax api 调用给出错误

问题描述

我正在学习 JS 并正在开发一个使用https://opentdb.com中的问题的琐事应用程序。我在调用 API 以根据所选类别和难度生成问题时遇到问题。我正在使用 Jquery/Ajax 库连接到 API,但是它给了我一个解析错误。我无法理解如何正确地做到这一点,在过去的几天里,我已经阅读了大量关于此的文档,并且我正在努力掌握这个概念。我尝试使用 vanilla JS(fetch() 等)来做,但没有成功。如果有人能指出我哪里出错了,我将不胜感激。

到目前为止我的代码:

const score = document.querySelector('#score');
const output = document.querySelector('#output');
const answerSelect = document.querySelector('#selAnswers');
const btn = document.querySelector('#btn');

const categories = [
  'Sports',
  'Art',
  'Vehicles',
  'History'
];

const difficulty = [
  'easy',
  'medium',
  'hard'
];

btn.addEventListener('submit', function(e) {
  e.preventDefault();

});

document.addEventListener('DOMContentLoaded', function() {

  let categorySelect = document.querySelector('#category');
  let difficultySelect = document.querySelector('#difficulty');

  let html = '';
  for (let item of categories) {
    // Appending Strings created using Template literals
    html += `<option>${item}</option>`;
  }
  categorySelect.innerHTML = html;

  for (let item of difficulty) {
    let opt = document.createElement('option');

    // <option> will use its .textContent as value if not explicitly defined
    opt.textContent = item;

    difficultySelect.append(opt);
  }
});

$.ajax({
  url: 'https://opentdb.com/api.php?amount=10',
  data: {},
  type: 'GET',
  dataType: 'jsonp',
  success: function(data) {
  },
  error: function(jqXHR, textStatus, ex) {
    console.log(`${textStatus}, ${ex}, ${jqXHR.responseText}`);
    alert(`${textStatus}, ${ex} ${jqXHR.responseText}`);
  }
});


//function

function getQuestion() {

  result.innerHTML = '';
  btn.innerHTML = '';

  let categoryOption = categories.value;
  let difficultyLevel = difficulty.value;
}
<!doctype html>
<html lang="en">

<head>
  <title>Trivia</title>
  <link rel='stylesheet' href='css/Trivia.css'>
</head>

<body>
  <h1>Trivia</h1>
  <div>Score: <span id="score">Correct 0 Wrong 0</span></div>
  <br>
  <div>
    <label>Select Category:</label>
    <select id='category'></select>
    <br>
    <label>Select Difficulty:</label>
    <select id='difficulty'></select>
  </div>
  <br><br>
  <div id="output"></div>
  <br>
  <div id="selAnswers"></div>
  <br>
  <button id="btn">Get First Question!</button>
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src='js/Trivia.js'></script>
</body>

</html>

标签: javascriptjqueryjsonajaxapi

解决方案


推荐阅读