Jake Jake - 3 months ago 17
Ajax Question

How to access JSON object's values with Polymer's <iron-ajax>?

I was able to do this with jQuery but stuck on Polymer. How can I retrieve and list out the values, e.g. "title" and "productID"? This doesn't seem asd sn't seem asd sn't seem asd sn't seem asd

<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">

<script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="bower_components/iron-list/iron-list.html">
</head>

<body>
<template is="dom-bind">
<iron-ajax url="bookeo.json" last-response="{{item}}" auto></iron-ajax>
<iron-list items="[[item.data]]" style="height:40em" as="customer">
<template>
<div class="item">
<b>[[customer.title]] - [[customer.productId]]</b>
</div>
</template>
</iron-list>
</template>
</body>
</html>


The first part of the JSON file

{
"data": [
{
"title": "John Smith",
"participants": {
"numbers": [
{
"peopleCategoryId": "adults",
"number": 4
}
]

},
"productId": "2129Y4KNB2DC9F",
"price":
"totalPaid": {
"amount": "0",
"currency": "USD"
}
},
(followed by more objects...)

Answer

You're actually pretty close. A few problems I found:

  1. You've misplaced as="customer" on iron-ajax (which does not have an as property) when it should actually be on iron-list.

  2. You're referencing productID when the data actually contains productId (note the last lowercase d).

  3. Your JSON is malformed, as price is missing a value.

This is what your code should look like:

<template is="dom-bind">
  <iron-ajax url="bookeo.json" last-response="{{item}}" auto></iron-ajax>
  <iron-list items="[[item.data]]" style="height:40em" as="customer">
    <template>
      <div class="item">
        <b>[[customer.title]] - [[customer.productID]]</b>
      </div>
    </template>
  </iron-list>
</template>

And your JSON should be something like this:

{
  "data": [
    {
      "title": "John Smith",
      "participants": {
        "numbers": [
          {
            "peopleCategoryId": "adults",
            "number": 4
          }
        ]
      },
      "productId": "2129Y4KNB2DC9F",

      "price": "1.23", /* NOTE: price data was originally missing */

      "totalPaid": {
        "amount": "0",
        "currency": "USD"
      }
    },
  ...
  ]
}

plunker

Comments