来自 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我尝试打印它。我错过了什么?如何将 JSON 从 API 调用传递到this.data变量?

xhr.send()不会返回您想要的内容。

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

简单地说,您需要在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);
}

最新更新