我创建了以下 polymer 元素:
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<dom-module id="task-list-app">
<style>
:host {
}
</style>
<template>
<iron-ajax auto url="../tasks.json" handle-as="json" on-response="handleResponse"></iron-ajax>
<template is="dom-repeater" items="{{todos}}">
<span>hello</span>
</template>
</template>
</dom-module>
<script>
Polymer({
is: "task-list-app",
created: function () {
this.todos = [];
},
handleResponse: function (data) {
this.todos = data.detail.response;
}
});
</script>
我通过以下方式在我的 index.html 中调用它:
<task-list-app></task-list-app>
我期望对于 todo 数组中返回的每个对象,一个 <span>
将被打印。但是,当我运行该应用程序时,我在控制台中得到以下输出:
Uncaught TypeError: Cannot read property 'todos' of undefined
在polymer.html line 1001
我不确定这里发生了什么以及如何引用从 ajax 响应中收到的数据。
最佳答案
首先,您用来遍历数据的第二个模板应该是“dom-repeat”而不是“dom-repeater”。其次,您可以直接将 iron-ajax 的响应绑定(bind)到循环模板。像这样,
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<dom-module id="task-list-app">
<style>
:host {
}
</style>
<template>
<iron-ajax auto url="../tasks.json" handle-as="json" last-response="{{ajaxResponse}}"></iron-ajax>
<template is="dom-repeat" items="[[ajaxResponse.todos]]">
<span>{{item.todoItem}}</span>
</template>
</template>
</dom-module>
<script>
Polymer({
is: "task-list-app"
});
</script>
所以您基本上是将 last-response 属性的值直接绑定(bind)到您的循环模板。
关于javascript - 使用 polymer ajax 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30591409/