html - 来自 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
变量?
解决方案
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);
}
推荐阅读
- devise - 如果用户电子邮件已经注册或存在,则通过设计轨道注册,然后只需向给定地址发送电子邮件以登录您的帐户?
- google-apps-script - 在自定义函数中使用内置函数
- sql-server - IF EXISTS 部分查询未执行
- c++ - 如何遍历具有两个节点的链接节点
- ruby-on-rails - 我的 rails 项目有两个不同的 I18n.load_path 和 I18n.locale
- ios - 当应用不在应用商店中时,Firebase 动态链接未在开发应用中打开
- css - 在一列中显示按钮和 ul 并居中
- neo4j - Neo4j 是否有更有效的方法来编写多个 where-contains?
- tensorflow - 带有手工构建的图像数据生成器的 keras fit_generator():内存不足
- javascript - 在 JS 中用不同的数组替换对象数组