如何在 Polymer-3.x 中点击按钮触发 iron-ajax?

How to trigger iron-ajax on button click in Polymer-3.x?

我正在创建一个使用铁的聚合物元素-ajax。这将命中 public API 以获取随机的狐狸 imageUrl 并在 DOM.

中显示

要求

单击 button,我想对 api 进行新的调用,这将给我新的 url。 目前我正在使用 <button type="button" onClick="window.location.reload();">。但这会刷新页面。

问题

我检查了这个 并将其更改为版本 3 解决方案。

class MyFox extends PolymerElement {
  static get template() {
    return html`
      <dom-bind>
      <template id="temp"> 
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse"
            id="apricot">
          </iron-ajax>

          <button type="button" onClick="window.location.reload();">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
      </template>
      </dom-bind>
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    var temp = document.querySelector('#temp');
    temp.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);

但是我收到以下错误。 侦听器方法handleResponse未定义

问题

如何在点击按钮时手动触发 iron-ajax,这样我就可以获得新的 response or imageUrl 而页面不会刷新?

您的网络组件中有几个错误

class MyFox extends PolymerElement {
  static get template() {
    return html`
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse">
          </iron-ajax>

          <button type="button" on-tap="nextImg">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    this.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);