質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
データ構造

データ構造とは、データの集まりをコンピュータの中で効果的に扱うために、一定の形式に系統立てて格納する形式を指します。(配列/連想配列/木構造など)

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

2251閲覧

【Fetch API】fetchしたデータがundefinedとなる。

退会済みユーザー

退会済みユーザー

総合スコア0

データ構造

データ構造とは、データの集まりをコンピュータの中で効果的に扱うために、一定の形式に系統立てて格納する形式を指します。(配列/連想配列/木構造など)

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2020/10/04 04:20

JavaScriptでクイズアプリを制作しているのですが、
①Open Trivia DBからデータをfetchで取得
②HTMLに表示
という流れを想定しています。
しかし受け取ったデータを表示しようとしたら[undefined]となります。
なぜか原因が分からず、モヤモヤしています。
分かる方がいたら是非教えていただければ嬉しいです。

index.html

1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7</head> 8<body> 9 <div id="container"> 10 11 <h2 id="title"></h2> 12 <div id="question"></div> 13 <div id="content"></div> 14 </div> 15 16 17 <script src="js/quiz.js"></script> 18</body> 19</html>

quiz.js

1class Quiz { 2 constructor(url) { 3 this.url = url; 4 } 5 fetchQuizData() { 6 return fetch(this.url) 7 .then(response => { 8 if(response.ok) { 9 response.json(); 10 } else { 11 throw new Error(); 12 } 13 }) 14 .then(jsonData => { 15 const dom = document.getElementById('question'); 16 dom.innerHTML = jsonData; 17 }) 18 .catch((error) => console.log(error)); 19 } 20} 21 22const quiz = new Quiz('https://opentdb.com/api.php?amount=10&type=multiple'); 23 24quiz.fetchQuizData();

よろしくお願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

返ってきたデータを確かめたところ、以下のようなデータ構造になっていました。(少し長いJSONコードです。すみません)

quiz.json

1{"response_code":0, 2"results":[ 3 {"category":"Entertainment: Video Games","type":"multiple","difficulty":"medium","question":"Which of the following created and directed the Katamari Damacy series?","correct_answer":"Keita Takahashi","incorrect_answers":["Hideki Kamiya","Shu Takumi","Shinji Mikami"]}, 4 {"category":"Art","type":"multiple","difficulty":"easy","question":"Who painted the Sistine Chapel?","correct_answer":"Michelangelo","incorrect_answers":["Leonardo da Vinci","Pablo Picasso","Raphael"]}, 5 {"category":"Entertainment: Music","type":"multiple","difficulty":"medium","question":"Who is the Pink Floyd song &quot;Shine On You Crazy Diamond&quot; written about?","correct_answer":"Syd Barrett","incorrect_answers":["John Lennon","David Gilmour","Floyd"]}, 6 {"category":"History","type":"multiple","difficulty":"medium","question":"Which of the following is NOT classified as a Semetic language?","correct_answer":"Sumerian","incorrect_answers":["Maltese","Akkadian","Mandaic"]},{"category":"Entertainment: Music","type":"multiple","difficulty":"easy","question":"Which of these is NOT the name of an album released by English singer-songwriter Adele?","correct_answer":"12","incorrect_answers":["19","21","25"]},{"category":"Entertainment: Cartoon & Animations","type":"multiple","difficulty":"hard","question":"In the web-comic Homestuck, what is the name of the game the 4 kids play?","correct_answer":"Sburb","incorrect_answers":["Homesick","Husslie","Hiveswap"]},{"category":"History","type":"multiple","difficulty":"medium","question":"What was the transfer of disease, crops, and people across the Atlantic shortly after the discovery of the Americas called?","correct_answer":"The Columbian Exchange","incorrect_answers":["Triangle Trade","Transatlantic Slave Trade","The Silk Road"]},{"category":"Entertainment: Board Games","type":"multiple","difficulty":"hard","question":"Some of the &quot;Fallen Empires&quot; cards from &quot;Magic: The Gathering&quot; were misprinted on the backs of which other card game?","correct_answer":"Wyvern","incorrect_answers":["Pokemon","Dominion","Yu-Gi-Oh"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"medium","question":"In &quot;Kingdom Hearts&quot;, who abducts Jasmine in the Lamp Chamber?","correct_answer":"Riku","incorrect_answers":["Riku Replica","Xaldin","Captain Hook"]}, 7 {"category":"Entertainment: Japanese Anime & Manga","type":"multiple","difficulty":"medium","question":"What is the name of the protagonist of the 2017 anime &quot;Land of the Lustrous&quot;?","correct_answer":"Phosphophyllite","incorrect_answers":["Watermelon Tourmaline","Cinnabar","Padparadscha"]}]}

そこで以下のように、jsonData.result[0].categoryなどとしてあげることでしっかりデータが取り出せました。(またコードの再利用性を高めるために、実際にHTML部分に表示させる操作はclass外に書きました。)

quiz.js

1class Quiz { 2 constructor(url) { 3 this.url = url; 4 } 5 fetchQuizData() { 6 return fetch(this.url) 7 .then(response => { 8 if(response.ok) { 9 return response.json(); 10 } else { 11 throw new Error(); 12 } 13 }) 14 .catch((error) => console.log(error)); 15 } 16} 17 18const quiz = new Quiz('https://opentdb.com/api.php?amount=10&type=multiple'); 19 20quiz.fetchQuizData() 21.then(jsonData => { 22 const dom = document.getElementById('question'); 23 dom.innerHTML = jsonData.results[0].category; 24});

●実際の画面
しっかり取得できています。

投稿2020/10/04 04:35

編集2020/10/04 04:38
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問