javascript - 简单的 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>
解决方案
推荐阅读
- forms - 如何使组合框在访问中可搜索?
- three.js - Three.js + Tween.js 补间多个对象的顶点
- java - 将 MobileFirst 7.0 迁移到 8.0 - 服务器类
- angular - 使用 Angular 4 反应形式添加新的动态表单控制器
- unix - 如何从 unix 的目录中提取文件(以数字命名)
- python - 在 Celery 中运行和弦时出现参数错误
- botframework - 设置 formflow 对话框字段值,以后不提示
- c - 使用 System V 信号量的 3 个进程进行同步
- c# - 从对象池中旋转游戏对象
- filenet-p8 - FileNet 配置管理器无法连接到 WebSphere Application Server