将来自铁ajax请求的返回值存储在变量中(Polymer)

Store returned values from the iron-ajax request in variables (Polymer)

本文关键字:变量 Polymer 存储 返回值 ajax 请求 将来      更新时间:2023-09-26

我第一次使用Polymers iron-ajax元素,遇到了一个问题,我认为这个问题很容易解决,但我无法在网上找到解决方案。

我使用iron-ajax元素检索用户详细信息,并用dom-repeat遍历它。用户的姓和名被放置在我创建的用于显示用户的自定义card元素中。除了无法将返回的id值存储在变量中之外,一切正常。我确信这是可能的使用数据绑定,但我不能让它工作。甚至当我尝试在JavaScript中使用getAttribute获取值时它也只返回null

在我的铁ajax请求下面的代码&可以找到响应,包括我笨拙地尝试获取id值{{item.id}}。为此,我创建了一个on-tap函数,当用户单击其中一张卡片时,该函数应该获得stdId属性的值。

<dom-module id="my-students-view">
<template>
  <style>
    :host {
      display: block;
    }
  </style>
  <!-- Iron-Ajax created connection and gets data -->
  <iron-ajax
    auto
    id="requestRepos"
    url="http://api.dev/user/"
    handle-as="json"
    loading="{{isloading}}"
    last-response="{{response}}"></iron-ajax>
  <!-- dom-repeat iterates the response -->
  <template is="dom-repeat" items="[[response.data]]" sort="sortData">
    <student-card
      id="studentCard"
      to="http://localhost:8080/profile-view/{{item.id}}"
      picsrc="../../images/anonymous.jpg"
      name="{{item.first_name}} {{item.last_name}}"
      stdId="{{item.id}}"
      on-tap="sendId"></student-card>
  </template>
</template>
<script>
Polymer({
  is: 'my-students-view',
  properties: {
    stdId: {
      notify: true,
    }
  },
  //Sort the array/data alphabetically
  sortData: function(a, b) {
    if(a.first_name < b.first_name) return -1;
    if(a.first_name > b.first_name) return 1;
    return 0;
  },
  //Try to get the id value of a the student card 
  sendId: function() {
    var idPropertie = this.$$("#studentCard");
    var idValue = idPropertie.getAttribute('stdId');
    console.log('the id is:' + idValue);
  },
});
</script>
</dom-module>

重写sendId函数:

sendId: function(event) {
  var idValue = event.model.item.id;
  console.log('the id is:' + idValue);
},