前提・実現したいこと
ご教授お願いします。
opne trivia という様々なクイズが保存されているDBからAPIを使用してデータを取得し、HTMLにて
出力するという簡単なアプリを作成しようとしています。
発生している問題・エラーメッセージ
取得したJsonデータをHTMLにて出力する際に文字化けを起こしてしまいます。
Which artist’s studio was known as 'The Factory'?
該当のソースコード
javascript
1const startBtn = document.getElementById('start'); 2const topContent = document.getElementById('topContent'); 3const center = document.getElementById('centerContent'); 4const down = document.getElementById('downContent'); 5const header = document.getElementById('header'); 6const content = document.getElementById('content'); 7let questionData; 8 9startBtn.addEventListener('click', () => { 10 waitingPage(); 11 startBtn.remove(); 12 asynchronousFunc().then(questionPage); 13 14}); 15 16const asynchronousFunc = () => { 17 return new Promise((resolve, reject) => { 18 fetch('https://opentdb.com/api.php?amount=10') 19 .then(response => response.json()) 20 .then(data => { 21 questionData = data; 22 resolve(); 23 }) 24 }); 25} 26 27const waitingPage = () => { 28 header.innerText = '取得中'; 29 content.innerText = '少々お待ちください'; 30} 31 32const questionPage = () => { 33 header.innerText = '問題1'; 34 createCategory(); 35 createLevel(); 36 createQuestion(); 37} 38 39const createCategory = () => { 40 const category = questionData.results[0].category; 41 const genre = document.createElement('h3'); 42 const genreContent = document.createTextNode('[ジャンル] ' + category); 43 genre.appendChild(genreContent); 44 topContent.appendChild(genre); 45} 46 47const createLevel = () => { 48 const difficulty = questionData.results[0].difficulty; 49 const level = document.createElement('h3'); 50 const levelContent = document.createTextNode('[難易度] ' + difficulty); 51 level.appendChild(levelContent); 52 topContent.appendChild(level); 53} 54 55const createQuestion = () => { 56 const question = questionData.results[0].question; 57 content.innerText = question; 58} 59
試したこと
fetchにてデータを取得した際の文字コードに問題があるのかと思い、fetchのオプジョンにて
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
と指定してみましたが、通信自体ができなくなりました。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/08/15 09:19