如何在聚合物中触发Ajax(<iron-ajax>)调用?

时间:2017-01-02 13:03:45

标签: ajax polymer

我只是想在一些javascript函数中触发ajax

我的代码在这里:

<template is="dom-bind" id="app"> 
<iron-ajax auto url="{{ path('polymer_get_file') }}" handle-as="json" last-response="{{ '{{attachmentResponse}}' }}">
</iron-ajax>
  <vaadin-grid items="{{attachmentResponse.results' }}">
    <table>
      <colgroup>
        <col name="index">
        <col name="file"/>
        <col sortable name="file"/>
        <col name="type"/> 
      </colgroup> 
    </table>
  </vaadin-grid></template><script> function onClick (){
   // Here i need to trigger iron-ajax } </script>

1 个答案:

答案 0 :(得分:3)

您可以致电<iron-ajax>的{​​{3}}:

<template is="dom-bind" id="app">
  <button on-tap="onClick">Send</button>
  <iron-ajax id="ajax" ...></iron-ajax>
</template>

<script>
  var app = document.getElementById('app');
  app.onClick = function() {
    this.$.ajax.generateRequest();
  };
</script>

HTMLImports.whenReady(() => {
  const app = document.getElementById('app');
  app.onClick = function() {
    this.response = null;
    this.$.ajax.generateRequest();
  };
  
  app.json = function(obj) {
    return JSON.stringify(obj, null, 2);
  };
});
<head>
  <base href="https://polygit.org/polymer+1.11.3/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-ajax/iron-ajax.html">
</head>
<body>
  <template is="dom-bind" id="app">
    <button on-tap="onClick">Send</button>
    <iron-ajax id="ajax"
               url="//httpbin.org/get"
               last-response="{{response}}"></iron-ajax>
    <pre>[[json(response)]]</pre>
  </template>
</body>

generateRequest()