我有这个函数,当它被调用时它会给我一个 JSON 返回值。
getJSON function(url, success){
var ud = '_' + +new Date,
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
为了调用该函数,我使用以下代码。
getJSON('https://newsapi.org/v1/articles?source=techcrunch&apiKey={APIKEY}', function(data){
//Stuff to be done with the data
});
然后我有一张纸卡,我想将获得的 JSON 值绑定(bind)到它。
<paper-card heading="Card Title">
<div class="card-content">{{json}}</div>
</paper-card>
我想做的是,以聚合方式声明 getJSON 函数的调用,调用该函数并将返回的 JSON 值设置为纸卡中的 {{json}}
数据元素。我已经尝试了超过 5 种方法来执行上述操作,但我无法做我想做的事。我是 polymer 新手,所以请帮助我。
最佳答案
而不是自己编写 getJSON()
方法,你可以使用 Polymer 的 <iron-ajax>
元素来为您获取数据。
新闻 API data看起来类似于这个 JSON 对象:
{
"status": "ok",
"source": "the-next-web",
"sortBy": "latest",
"articles": [{
"author": "TNW Deals",
"title": "4 offers from TNW Deals you won’t want to miss",
"description": "We’ve featured some great offers from TNW …",
}, {
"author": "Bryan Clark",
"title": "Amazing 4k video of the Northern Lights",
"description": "Tune in, and zone out …",
}]
}
我假设您想显示 articles[]
中的每篇文章数组。
<iron-ajax>
元素可以从新闻 API 请求数据并将服务器响应存储在 lastResponse
中,您可以将其绑定(bind)到可在模板中使用的属性。
在下面的示例中,我们看到 last-response="{{data}}"
, <iron-ajax>
将把 News API 响应输出到 data
(即,类似于设置 this.data = response
,其中 response
是上面的 JSON 对象)。考虑到前面提到的数据形状,我们知道data.articles
将访问文章数组,可以将其传递给 dom-repeat
对于迭代:
<template>
<iron-ajax url="https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=|APIKEY|"
auto
last-response="{{data}}">
</iron-ajax>
<template is="dom-repeat" items="[[data.articles]]">
<paper-card heading="[[item.title]]">
<div class="card-content">
<p>[[item.description]]</p>
</div>
</paper-card>
</template>
</template>
或者,如果您需要事先强制操作响应,您可以 setup an event listener对于 <iron-ajax>.response
事件。事件详细信息包含 .response
中的数据。您可以处理/修改该数据,并将结果分配给 this.articles
,绑定(bind)在 dom-repeat
中.
<template>
<iron-ajax url="https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=|APIKEY|"
auto
on-response="_onResponse">
</iron-ajax>
<template is="dom-repeat" items="[[articles]]">
<paper-card heading="[[item.title]]">
<div class="card-content">
<p>[[item.description]]</p>
</div>
</paper-card>
</template>
</template>
<script>
Polymer({
...
_onResponse: function(e) {
var data = e.detail.response;
// do something with data...
// set this.articles for dom-repeat
this.articles = data;
}
});
</script>
关于javascript - Polymer 中的数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544340/