実現したいこと
ローカルのjsonファイルをfetchで読み込み、その中の辞書データを取得し、そのデータを特定の関数の引数に設定したい。
発生している問題・分からないこと
responseは得られるが、そのresponseからresponse.json()でデータ(data)を取得しようとしても取得できない。
エラーメッセージ
error
1(下のコードでは書いてないですが、.catch(e => alert('here'))で'here'がwindowに表示されます。)
該当のソースコード
javascript①
1 function make_pd_categories(path){ 2 fetch(path) 3 .then(response => response.json()) 4 .then(data => { 5 make_pd_forms(data); 6 }); 7 } 8 9 function make_pd_forms(data){ 10 const prediction_menu = document.getElementById("pf_menu5"); 11 for (let d of data){ 12 var newPDForm = document.createElement("form"); 13 14 newPDForm.action = 'try_add_pc?category=${d.title}'; //formの遷移先を設定 15 newPDForm.method = 'post'; 16 newPDForm.enctype = "multipart/form-data"; 17 newPDForm.className ="prediction_form"; 18 19 newPDForm.insertAdjacentHTML('beforeend', '<div><p>${d.title}</p></div>'); //お題を追加 20 newPDForm.insertAdjacentHTML('beforeend', make_answer_area(d.type, d.contents)); //回答欄を追加 21 newPDForm.insertAdjacentHTML('beforeend', '<button type="submit" class="pure-button pure-button-primary">決定</button>'); //回答ボタンを追加 22 prediction_menu.appendChild(newPDForm); 23 } 24 }
javascript②
1 function set_contents(chart_path, history_path, prediction_path){ 2 make_chart(chart_path); 3 hs_sentences(history_path); 4 make_pd_categories(prediction_path); 5 }
html
1<!DOCTYPE html> 2<html><meta charset="UTF-8"> 3 <meta name="viewport" 4 content="width=device-width, initial-scale=1.0"> 5 <link rel="stylesheet" href="static/css/pure-min.css"> 6 <link rel="stylesheet" href="static/css/style.css?v=18"> 7 <link rel="stylesheet" href="static/css/team_color.css"> 8 <body onload="set_contents('{{ url_for('static', filename='graph_csv_files/graph_大谷翔平.csv') }}', '{{ url_for('static', filename='hs_sentences_files/history_大谷翔平.txt') }}', '{{ url_for('static', filename='pd_json_files/prediction_大谷翔平.json') }}')"><div class="content"> 9 <h1> 10 <div><a id="home" href="/">Earthliete</a></div> 11 <div id="header-menu"> 12 <a id="editpf" href="/"></a> | 13 <a id="login" href="/login"></a> 14 </div> 15 </h1>
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
fetch内のdataの文字をresやjsonに変更してみたが解決しませんでした。
pathをjsonファイルではなくtxtファイルにして、取得するデータをresponse.text()にしたらデータを取得できました。(txtファイルなら読み込めるのに、なぜかjsonファイルは読み込めません。)
補足
読み込むファイル(prediction_大谷翔平.json)の内容は以下の通りです。
[{"title": "今シーズンのHR数は?", "type": 0, "contents": ""}, {"title": "シーズンMVPを獲る?", "type": 1, "contents": ["獲る, "獲らない"]}]
また、alert(response.json())でresponse.jsonについて確認すると、promiseオブジェクトとなっていることが確認できました。

回答1件
あなたの回答
tips
プレビュー