LoginSignup
2
2

More than 5 years have passed since last update.

Polymer core-ajax の使い方

Posted at

Polymerのcore-ajaxの使い方。

まずは、index.html

index.html
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./bower_components/webcomponentsjs/webcomponents.js"></script>
  <link rel="import" href="my-topics.html">
</head>
<body fullbleed vertical layout unresolved>
  <my-topics></my-topics>
</body>
</html>

my-topicsというCustom Elementに実際の処理を書く。JSONで、とあるサーバからデータを取得する、という想定。本当はJSONPで取りたかったんだけど、それは次回までの課題で...

my-topics.html
<polymer-element name="my-topics" attributes="">
  <link rel="import" href="bower_components/core-ajax/core-ajax.html">
  <template>
    <core-ajax auto url="http://url.to.api/"
      handleAs="json"
      on-core-response="{{handleResponse}}"></core-ajax>
    <table id="topics">
      <tr template repeat="{{topic in topics}}">
        <td><a href="{{topic.uri}}">{{topic.title}}</a></td>
      </tr>
    </table>
  </template>
  <script>
    Polymer('my-topics',{
      handleResponse: function(ev,res){
        this.topics = res.response;
      }
    });
  </script>
</polymer-element>

core-ajaxon-core-responseは、ajaxで取得でき時に呼ばれ関数を指定する。実際のレスポンスは、指定した関数の第2引数に格納される。実際の第1引数(ev)と第2引数(res)には次のような値が入る。

>ev
CustomEvent {detail: Object, clipboardData: undefined, path: NodeList[12], cancelBubble: false, returnValue: true}

>res
Object {response: Array[398], xhr: XMLHttpRequest}
2
2
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
2
2