如何在Polymer-3.x中单击按钮时触发铁ajax?

时间:2018-08-28 07:32:41

标签: polymer polymer-3.x iron-ajax

我正在创建一个使用铁ajax的聚合物元素。这将通过公共API来获取随机的Fox imageUrl并在DOM中显示。

要求

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

问题

我经历了这个StackOverflow solution,并将其更改为版本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未定义

fox error

问题

如何在单击按钮时手动触发iron-ajax,以便获得新的response or imageUrl并且页面不会刷新?

1 个答案:

答案 0 :(得分:1)

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

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);
相关问题