目的
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" }