[英]How to trigger iron-ajax on button click in Polymer-3.x?
I am creating a polymer element which uses iron-ajax.我正在创建一个使用铁阿贾克斯的聚合物元素。 This will hit a public API to fetch a random fox imageUrl and dispaly in DOM.这将访问公共 API 以获取随机的狐狸 imageUrl 并在 DOM 中显示。
Requirement要求
On clicking button
, i want to make a new call to the api, this will give me new url.单击button
,我想对 api 进行新调用,这会给我新的 url。 Currently i am using <button type="button" onClick="window.location.reload();">
.目前我正在使用<button type="button" onClick="window.location.reload();">
。 but this refreshes page.但这会刷新页面。
Problem问题
I went through this StackOverflow solution and changed it to version-3 solution.我浏览了这个StackOverflow 解决方案并将其更改为版本 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);
But i am getting the following error.但我收到以下错误。 listener method handleResponse
not defined未定义侦听器方法handleResponse
Question题
How to manually trigger iron-ajax
on button click, so I can get new response or imageUrl
and the page is not refreshed?如何在单击按钮时手动触发iron-ajax
,以便我可以获得新的response or imageUrl
并且页面不会刷新?
There are a couple errors in your web component您的 Web 组件中有几个错误
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.