LoginSignup
20
15

More than 5 years have passed since last update.

ES6 と Promise と XMLHttpRequest で json を取るサンプル

Last updated at Posted at 2015-07-11

目的

ES6 で jQuery の $ajax を使わず非同期で json のデータをとりたい

ファイル構成

├── dest
│   └── app.js
├── index.html
├── data.json
├── package.json
└── src
    ├── app.js
    └── utils.js

インストールなど

package.json
{
  "devDependencies": {
    "babelify": "^6.1.2",
    "browserify": "^10.2.6",
    "watchify": "^3.2.3"
  },
  "scripts": {
    "watch": "watchify -t babelify src/app.js -o dest/app.js -v"
  }
}
$ npm install
$ npm run watch
src/app.js
import {http} from './utils';


var url = '../data.json';
http.get(url).then(res => {
    let data = JSON.parse(res);
    console.log(data);
}).catch(e => {
    console.error(e);
});
src/utils.js
export default {
    http: {
        get: (url) => {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.onload = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        resolve(xhr.response);
                    } else {
                        reject(new Error(xhr.statusText));
                    } };
                xhr.onerror = () => {
                    reject(new Error(xhr.statusText));
                };
                xhr.send(null);
            });
        }
    }
};
index.html
<!doctype html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>ES6</title>
    </head>
    <body>
        <script src="dest/app.js"></script>
    </body>
</html>
data.json
{
  "1": "foo",
  "2": "bar"
}

動作確認

python -m SimpleHTTPServer 8000

Firefox 開発ツールの console などで確認

Object { 1: "foo", 2: "bar" }

参考

20
15
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
20
15