[英]How to read data on client side from a file scoped variable set on server?
I'm new to meteor (and javascript) and trying to make a simple app that will read some data from an web api and create a chart. 我是流星(和javascript)的新手,正在尝试制作一个简单的应用程序,该应用程序将从Web api读取一些数据并创建图表。
The data that I retrieve doesn't need to be stored in a database. 我检索到的数据不需要存储在数据库中。 My naive approach consists of creating a variable with file scope to store the data, making an http request on the server upon startup and then reading the data from the variable on the client to create a chart using d3.js.
我的幼稚方法包括创建一个具有文件作用域的变量来存储数据,启动时在服务器上发出一个http请求,然后从客户端上的变量读取数据以使用d3.js创建图表。 Later I will add code to retrieve the data at a specified interval, but I just want to figure out how to pass the data from the server to the client.
稍后,我将添加代码以指定的时间间隔检索数据,但是我只想弄清楚如何将数据从服务器传递到客户端。
Here's the relevant portions of the js file... 这是js文件的相关部分...
var dayData = "";
if (Meteor.isServer) {
Meteor.startup(function () {
dayData = HTTP.call("GET",
"http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG&f=nb2b3");
console.log(dayData.content); // check to see data exists
});
}
if (Meteor.isClient) {
Template.hello.rendered = function () {
var self = this;
if (! self.handle) {
self.handle = Deps.autorun(function () {
d3.csv.parse(dayData.content, function(data) {
d3.select("#example")
.datum(data)
.call(chart);
});
});
}
};
Within the client portion of the code, the dayData is set to "" and not the contents of the result object that I have printed to the terminal on the server side code. 在代码的客户端部分中,dayData设置为“”,而不是我已经打印到服务器端代码的终端上的结果对象的内容。
My first question is why doesn't the dayData variable contain the result object from the http request when reading it on the client? 我的第一个问题是,为什么在客户端上读取数据时,dayData变量不包含http请求的结果对象? My second question is what is a best practice for reading remote data on the server and accessing that data on the client in some way that doesn't require using a database?
我的第二个问题是,以不需要使用数据库的某种方式读取服务器上的远程数据并在客户端上访问该数据的最佳实践是什么?
1) On the client, the variable Meteor.isServer
is false
, so the if
block is not executed, so the HTTP call does not happen and the variable is not initialized. 1)在客户端上,变量
Meteor.isServer
为false
,因此不执行if
块,因此不会发生HTTP调用并且变量不会初始化。
2) Use a method: 2)使用方法:
var dayData;
...
if(Meteor.isServer) {
Meteor.methods({
getDayData: function() {
return dayData;
},
});
}
if(Meteor.isClient) {
Meteor.startup(function() {
Meteor.call('getDayData', function(error, result) {
dayData = result;
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.