首页 > 解决方案 > 来自 Web API 的聚合物数据绑定

问题描述

我想将一些数据绑定到来自服务器的命令(通过按下按钮)的变量。在服务器上,我有一个将返回 JSON 对象的函数(已经过测试,如果我直接打开 API 链接,我会得到正确的 JSON 格式)。但是,无论我做什么,变量都保持未定义。我有一个按钮和一个表格(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我试图打印它的两次。我错过了什么?如何将 API 调用中的 JSON 传递给this.data变量?

标签: htmldata-bindingpolymerpolymer-1.0

解决方案


xhr.send()不返回你想要的。

你需要先学习 XmlHttpRequest。这是文档。还有一些简单的例子

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

另外,为什么要使用 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);
}

推荐阅读