【问题标题】:Polymer data binding from Web API来自 Web API 的聚合物数据绑定
【发布时间】:2018-11-21 18:30:49
【问题描述】:

我想将一些数据绑定到来自服务器的命令(通过按下按钮)的变量。在服务器上,我有一个返回 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 变量?

【问题讨论】:

    标签: html data-binding polymer polymer-1.0


    【解决方案1】:

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

    你需要先学习 XmlHttpRequest。这里是documentation。还有一些简单的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);
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多