来自 Web 的 Polymer 数据绑定 API

Polymer data binding from Web API

我想根据服务器的命令(通过按下按钮)将一些数据绑定到变量。在服务器上我有一个函数,它将 return 一个 JSON 对象(这已经过测试,如果我直接打开 API link,我确实得到了正确的 JSON 格式)。但是,无论我做什么,变量都保持未定义状态。我有一个按钮和一个 table(px-data-table 是框架的一部分,应该能够显示 JSON 格式的数据):

<button id="runPredictionButton">
    <i>Button text</i>
</button>
<px-data-table 
      table-data$="{{data}}"
</px-data-table>
<div class="output"></div>   

我正在处理按钮按下并按如下方式定义变量:

  <script>
    Polymer({
      is: 'custom-view',
      properties: {
        data: {
          type: Object,
          notify: true
        }
      },
    ready: function() {
      var self = this;
      this.$.runPredictionButton.addEventListener('click', function() {
          filerootdiv.querySelector('.output').innerHTML = 'Is here';    
          var xhr = new XMLHttpRequest();
          this.data = xhr.open("GET", "API/predict") //as mentioned, API/predict returns a valid JSON
          console.log("This data is:" + this.data);
          this.data = xhr1.send("API/predict","_self")
          console.log("This data is_:" + this.data);
      });
    }
  });      
  </script>

出于某种原因,在控制台上 this.data 两次显示为 undefined 我正在尝试打印它。我错过了什么?如何将 JSON 从 API 调用传递给 this.data 变量?

xhr.send() 没有 return 你想要的。

你需要先学习XmlHttpRequest。这里是documentation. And some easy examples

简单地说,您需要在 xml 变量上收听 onreadystatechange。在那里您将能够从服务器获取数据。

另外,你为什么要使用 addEventListener。您可以简单地设置 on-click.

<button id="runPredictionButton" on-click="getDataFromServer">
    <i>Button text</i>
</button>

然后您可以定义 javascript 函数,每次用户单击按钮时都会调用该函数。

getDataFromServer: function() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "API/predict");
  xhr.send("API/predict","_self");
  xhr.onreadystatechange = function() {
   // 4 = data returned
   if(xhr.readyState == 4) {
     // 200 = OK
     if (this.xhttp.status == 200) {
       // get data
       this.data = xhr.responseText;
     }
   }
  }.bind(this);
}