我正在使用 Polymer 2,并且想要绑定(bind)本地 json 文件中的数据。但每次我尝试它都无法仅获取 json 文件。
我尝试过两种方法来实现它:
1) 使用
<iron-ajax url="data/employees.json" handle-as="json" last-response="{{items}}" auto>
</iron-ajax>
文件夹结构:
<iron-list items="{{items}}" as="item">
<template>
<div class="item">
<b>[[item.nickname]]</b>
<p>[[item.phone]]</p>
</div>
</template>
</iron-list>
我还导入了iron-ajax和iron-list
2)使用$.get
从start中的json中提取数据并将其放入变量中以将其绑定(bind)到 View 。
<script>
class IronListClass extends Polymer.Element {
static get is() {return 'iron-comp'}
ready() {
super.ready();
var that = this;
// $.get('data/employees.json', function(data) {
// that.employees = $.parseJSON(data).results;
// console.log(that.employees);
// });
$.get('data/employees.json', function(data) {
this.employees = $.parseJSON(data).results;
console.log(this.employees);
}.bind(this));
}
}
window.customElements.define(IronListClass.is, IronListClass);
</script>
也尝试过那个=这个。
最佳答案
您可以按照以下示例加载 json 文件,因为它已经在我的应用程序中运行。
<iron-ajax
auto
url$="{{url}}"
handle-as="json"
last-response="{{loadedItems}}"
>
</iron-ajax>
...
static get properties() { return {
url :{
type:String,
value() {return "./data/employees.json"; }
}
...
static get observers() { return ['checkJsonFileLoaded(loadedItems)']}
checkJsonFileLoaded(j) {
if (j) {
this.set('items', j);
console.log(items); //u should see the loaded json file. If so than the problem is iron-list (to publish the result)
}
}
关于javascript - 无法从本地 json 绑定(bind)数据来查看 polymer 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006684/