6
1
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

【HTML】サーバを立てずに、HTMLで同じディレクトリにあるJSONを読み込む

Last updated at Posted at 2024-07-06

どうもこんにちは。

今回は、サーバを立てずにHTMLで同じディレクトリにあるJSONを読み込むのに苦戦したので、その方法をメモとして残します。

とりあえずHTMLで雛形作る

index.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Sample</title>
    </head>
    <body>
        <div class="box">
            <div class="display-area">
                <div>
                    名前: <span id="name-area"></span>
                </div>
                <div>
                    年齢: <span id="age-area"></span>
                </div>
            </div>
        </div>
        
        <script>
            const source_src = 'sample_data.json';
            var xhr = new XMLHttpRequest();
            xhr.open('GET', source_src, false);
            xhr.send(null); // ココ!!
            
            if (xhr.status === 200) {
                var data = JSON.parse(xhr.responseText);

                var nameAreaElement = document.querySelector('.name-area');
                var ageAreaElement = document.querySelector('.age-area');

                nameAreaElement.textContent = data["datas"]["name"];
                ageAreaElement.textContent = data["datas"]["age"];
            }
        </script>
    </body>
</html>

サンプルJSON

sample_data.json
"datas": {
    "name": "テスト太郎",
    "age": 30
}

さてさて...

作成したindex.htmlのファイルパスをコピーしてブラウザで開くと...

Access to XMLHttpRequest at 'file:///Users/testuser01/sample.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, isolated-app, brave, https, chrome-untrusted, data, chrome-extension, chrome.

CORS制約に反していると言われてしまいます。

解決するには

以下のコマンドをターミナルで実行します。

# windowsの場合
chrome.exe --disable-web-security --user-data-dir="C:/ChromeDevSession"

# macの場合
open -na "Google Chrome" --args --disable-web-security --user-data-dir="$HOME/ChromeDevSession"

必ず、Chromeを完全に終了した状態で実行してください。
バックグラウンドで動いている状態では実行できないので、注意してください。

これでJSONファイルを読み込むことができるようになります。

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1