如何使用Polymer的<iron-ajax>访问JSON对象的值?

时间:2016-08-21 17:17:21

标签: json ajax polymer

我能够用jQuery做到这一点,但坚持使用Polymer。如何检索和列出值,例如“title”和“productID”?这看起来并不像看起来似乎并不像其他人一样

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

JSON文件的第一部分

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

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

2 个答案:

答案 0 :(得分:1)

这应该有效:

Product

答案 1 :(得分:0)

你其实非常接近。我发现了一些问题:

  1. iron-ajax iron-list上没有as="customer"属性的as错误地放在plunker上。

  2. 当数据实际包含productID时,您引用了productId(请注意最后一个小写d)。

  3. 您的JSON格式错误,因为price缺少值。

  4. 这就是你的代码应该是这样的:

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

    你的JSON应该是这样的:

    {
      "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"
          }
        },
      ...
      ]
    }
    

    {{3}}