Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - Using polymer ajax response

I have the following polymer element which I have created:

<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>

I am calling this inside my index.html by doing:

<task-list-app></task-list-app>

I am expecting that for every object returned in the todo array, a <span> will be printed. However, when I run the app, I get the following output in the console:

Uncaught TypeError: Cannot read property 'todos' of undefined

in polymer.html line 1001

I am not sure what is happening here and how to reference the data received back from the ajax response.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all second template that you are using to loop through your data should be a "dom-repeat" and not a "dom-repeater". Secondly you can directly bind the response of iron-ajax to your looping template. Like this,

<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>

So you are basically binding value of last-response property to your looping template directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...