对蹩脚的标题表示歉意,但我找不到更好的东西。
所以这是我的问题:我使用iron-ajax获取数据,我在dom-repeat中绑定(bind)“on-response”并获取一个表格。很好。
但我还想访问我的 javascript 部分中的 ajax-response 作为变量,因此我可以使用 .length 等方法在“for”循环中使用。
这是我迄今为止尝试过的方法,通过阅读此论坛上的其他帖子,但不起作用:
<iron-ajax id="videosAjax" auto
url="http://mysuperawesome/service"
params='{}'
handle-as="json"
last-response="{{ajaxResponse}}"></iron-ajax>
<template is="dom-repeat" items="{{videosList}}">
<div class="colM">[[item.id]]</div>
</template>
和脚本部分:
<script>
Polymer({
is: 'videos',
ajaxResponse: function (data) {
this.videosList = data.detail.response;
console.log(this.videosList);
},
...
this.async(function () {
var count = this.videosList.length;
document.getElementById("videosCount").innerText = count;
</script>
但是不,console.log 仍然返回“undefined”:(
最佳答案
您的示例有 last-response="{{ajaxResponse}}"
,它将响应绑定(bind)到名为 ajaxResponse
的属性,这将允许模板中的其他元素绑定(bind)到它 ( jsbin )。
由于您想通知回调,因此您可以使用 on-response="METHOD"
,其中 METHOD
是 Polymer 对象上的方法的名称。实际上,该方法看起来与您的示例当前的 ajaxResponse()
非常相似。
这是一个工作演示(基于 iron-ajax/demo/index.html
):
<!DOCTYPE html>
<html>
<head>
<base href="https://polygit.org/polymer+:master/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="iron-ajax/iron-ajax.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<iron-ajax auto url="https://www.googleapis.com/youtube/v3/search"
params='{"part":"snippet", "q":"polymer", "key": "AIzaSyAuecFZ9xJXbGDkQYWBmYrtzOGJD-iDIgI", "type": "video"}'
handle-as="json"
on-response="handleResponse"
debounce-duration="300"></iron-ajax>
</template>
<script>
Polymer({
is: 'x-foo',
handleResponse: function(e) {
console.log(e.detail.response);
}
});
</script>
</dom-module>
</body>
</html>
关于javascript - 获取 Iron-ajax 响应作为 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37349471/