[英]How do I get data from server route to javascript? Nodejs Express pug
I am pretty new at this so I hope i'm asking the right question, and approaching this the right way. 我在这方面还很新,所以我希望我问一个正确的问题,并以正确的方式来解决这个问题。 I am trying to get data from the server. 我正在尝试从服务器获取数据。 I have successfully passed it through a route to a pug page, but the javascript on that page does not have access to these objects. 我已成功通过路由将其传递给哈巴狗页面,但该页面上的javascript无法访问这些对象。 Here is the server code. 这是服务器代码。 Also posted is the client side javascript where I don't have access to the objects passed to the pug page. 还发布了客户端javascript,其中我无权访问传递给pug页面的对象。
router.get('/stockView', ensureAuthenticated, function(req, res, next){
var s = req.user.stocks;
var t = [];
// get array of stock symbols
for(var stock in s)
{
if (isNaN(parseInt(stock)))
{
}
else
{
s.push(req.user.stocks[stock].symbol);
}
}
//pull historic data from yahoo-finance
yahooFinance.historical({
symbols: ['AAPL','YHOO'],
from: '2012-01-01',
to: '2012-02-28',
period: 'd' // 'd' (daily), 'w' (weekly), 'm' (monthly), 'v' (dividends only)
}, function (err, quotes) {
if(err){
// do nothing
}else{
res.render('stockView', {title: 'Stock View', user: req.user, stocks: quotes, mystocks: s, tickers: t });
}
});
});
// *********javascript code in stockView.pug file****************
script(type='text/javascript').
$(function(){
var tickers = #{title};
It doesn't work like that, Pug allows you to only handle the view and hence it directly renders the html view there. 它不是那样工作的,Pug只允许您处理视图,因此它直接在此处呈现html视图。 Pug Can only render views (HTML), It won't be able to give the javascript there access to the variables available to pug. Pug只能呈现视图(HTML),它将无法使javascript在那里访问可用于pug的变量。
You can use Ajax or Socket.io instead so your javascript code on the client side is connected with the javascript code you write on the server-side. 您可以改用Ajax或Socket.io,以便将客户端的javascript代码与您在服务器端编写的javascript代码连接起来。
That's Why we've technologies like socket.io and ajax, they allow the client side to be in touch with the backend and with Node I prefer to use Socket.io. 这就是为什么我们拥有诸如socket.io和ajax之类的技术的原因,它们允许客户端与后端以及与我更喜欢使用Socket.io的Node联系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.