【问题标题】:How to trigger iron-ajax on button click in Polymer-3.x?如何在 Polymer-3.x 中单击按钮时触发 Iron-ajax?
【发布时间】:2018-08-28 07:32:41
【问题描述】:

我正在创建一个使用 Iron-ajax 的聚合物元素。这将访问公共 API 以获取随机狐狸 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未定义

问题

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

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • @pascal 感谢您抽出时间并提供解决方案 :)
    • 需要将事件从 on-tap 更改为 on-click 以使代码正常工作。编辑待定,因此在此处添加为评论。
    • 不,因为我在我的编辑拒绝中声明最好将点击与聚合物一起使用,因为点击与桌面点击一样可以进行移动点击。
    • @PascalL。 Polymer 1 使用 recommended listening to tap 而不是 click 以实现跨平台一致性,但此建议是 dropped in Polymer 2,因为现代移动浏览器不再需要它。
    猜你喜欢
    • 2014-09-15
    • 2019-12-10
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多