LoginSignup
26
26

More than 5 years have passed since last update.

外部ファイルのjsonを読み込んで使う

Last updated at Posted at 2015-12-06

長いリストなどローカルに持ってるけど、外部ファイルに置いておくときなど、そのファイルを読み込むときに使う。

hoge.js
        httpObj = new XMLHttpRequest();
        httpObj.open("get", "./js/group.json", true);
        httpObj.onload = function(){
                var myData = JSON.parse(this.responseText);
                var txt = "";
                for (var i=0; i<myData.length; i++){
                   var option = document.createElement("option");
                    option.innerText = myData[i].name;
                    option.value=myData[i].value;
                    document.getElementById("group_select").appendChild(option); 
                }

            }
       httpObj.send(null);

openメソッドはopen(HTTPリクエストメソッド,発行URL,非同期リクエストをするかどうか)
sendメソッドはsend(リクエストボディーの文字列)

ex)
httpRequest.send('param1=value1&param2=value2');

このようなかんじで使うみたい。

参考:http://webos-goodies.jp/archives/50548720.html

ちなみに、Chromeでデバッグをするときはローカルであれなんであれ外部jsonファイルを読み込もうとすると怒られるので、

terminal
open -a Google\ Chrome --args --allow-file-access-from-files

外部ファイルをアクセスできる設定をつけてchromeを開いてデバッグする。

26
26
1

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
26
26