JavaScript
HTML5
fetch

今後に備えてFetch APIを使ってみる。

More than 1 year has passed since last update.

検証環境

  • MacOSX EL Caption 10.11.6
  • Google Chrome バージョン 52.0.2743.82 (64-bit)
  • Mac標準PHPのビルドインサーバーで確認
php -S localhost:3000

画像取得

get-image.html
<html>
<title>Fetch Test</title>
<body>
<img width=100>
<script>
var image1 = document.querySelector('img');

var request1 = new Request('images/logo.png');

fetch(request1)
.then(function(response) {

  console.log('type',                     response.type);
  console.log('ok',                       response.ok);
  console.log('status',                   response.status);
  console.log('statusText',               response.statusText);
  console.log('url',                      response.url);
  console.log('body',                     response.body);
  console.log('bodyUsed',                 response.bodyUsed);
  console.log('Content-Type',             response.headers.get('Content-Type'));
  console.log('Accept-Encoding',          response.headers.get('Accept-Encoding'));
  console.log('Cache-Control',            response.headers.get('Cache-Control'));
  console.log('Connection',               response.headers.get('Connection'));
  console.log('Content-Security-Policy',  response.headers.get('Content-Security-Policy'));

  return response.blob();
})
.then(function(blob1) {

  var objectURL = URL.createObjectURL(blob1);
  console.log('objectURL', objectURL);

  image1.src = objectURL;
});
</script>
</body>
</html>

Json取得

data/data1.json
{
  "employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
  ]
}
get-json.html
<html>
<title>Fetch Test</title>
<body>
<ul></ul>
<script>
var list1 = document.querySelector('ul');

var request1 = new Request('data/data1.json');

fetch(request1)
.then(function(response) {

  console.log('type',                     response.type);
  console.log('ok',                       response.ok);
  console.log('status',                   response.status);
  console.log('statusText',               response.statusText);
  console.log('url',                      response.url);
  console.log('body',                     response.body);
  console.log('bodyUsed',                 response.bodyUsed);
  console.log('Content-Type',             response.headers.get('Content-Type'));
  console.log('Accept-Encoding',          response.headers.get('Accept-Encoding'));
  console.log('Cache-Control',            response.headers.get('Cache-Control'));
  console.log('Connection',               response.headers.get('Connection'));
  console.log('Content-Security-Policy',  response.headers.get('Content-Security-Policy'));

  return response.json();

})
.then(function(json) {
  for(var i = 0; i < json.employees.length; i++) {
    var item = document.createElement('li');
    item.innerHTML = json.employees[i].firstName + json.employees[i].lastName;
    list1.appendChild(item);
  }
});

</script>
</body>
</html>

Form送信

send-from.html
<html>
<title>Fetch Test</title>
<body>
<form>
<input type="text" name="comment" value="テスト">
</form>
<script>

var form1 = document.querySelector('form');

fetch('/save.php', {
  method: 'POST',
  body: new FormData(form1)
})
.then(function(response) {
  return response.json()
})
.then(function(json) {
  console.log(json);// Object {コメント保存したよ: "テスト"}
})

</script>
</body>
</html>
save.php
<?php
$arr = array('コメント保存したよ' => $_POST['comment']);
echo json_encode($arr);

所感

  • thenrableな感じがスマート。
  • Safariで動かないのではやく実装したらいいと思う。 (2016/08/01現在)
  • FireFox, Chromeで動いた。
ReferenceError: Can't find variable: fetch

参考

https://fetch.spec.whatwg.org/
https://developer.mozilla.org/ja/docs/Web/API/Fetch_API