简体   繁体   中英

Using Polymer iron-ajax in repeating template

How do I load a json file and use the data in a repeating template? This code doesn't produce anything:

<dom-module id="name-list">
    <template>
        <iron-ajax auto url="names.json" handleAs="json" lastResponse="{{data}}"></iron-ajax>
        <template is="dom-repeat" items="{{data}}">
            <div>First name: <span>{{item.firstName}}</span></div>
            <div>Last name: <span>{{item.lastName}}</span></div>
        </template>
    </template>
</dom-module>

<script>
    Polymer({
        is: "name-list"
    });
</script>

Here's my json file (Edit: corrected after vasek's reply):

{
    [
        {
            "firstName": "John",
            "lastName": "Smith"
        },{
            "firstName": "Jane",
            "lastName": "Doe"
        }
    ]
}

I'd like to have the following:

<div>First name: <span>John</span></div>
<div>Last name: <span>Smith</span></div>
<div>First name: <span>Jane</span></div>
<div>Last name: <span>Doe</span></div>

I'm including iron-ajax elsewhere in my code. I've already tested the general functionality. It works, just not in the context of data-binding.

Firstly as vasek says, your JSON is incorrect. dom-repeat needs an array to iterate over and your JSON is currently returning an object. Secondly, you are accessing the properties on the iron-ajax element incorrectly. As the docs state

In order to configure camel-case properties of elements using attributes, dash- case should be used in the attribute name.

You are trying to set handleAs and lastResponse . In order to do these you need to change them to the dash-case:

<iron-ajax auto url="names.json" handle-as="json" last-response="{{data}}"></iron-ajax>

Otherwise, everything else should work correctly.

Your json file is in wrong format. It should be like this:

    [
        {
            "firstName": "John",
            "lastName": "Smith"
        },
        {
            "firstName": "Jane",
            "lastName": "Doe"
        }
    ]

I was also stuck with a similar code, unfortunately the above answers didn't solve the issue for me. However, when I put the <iron-ajax> element after the <template is="dom-repeat"> , it worked for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM