[英]Node.js / Express - How to access 'req' in JavaScript
So I have a page which is loaded called tournament/:key
, which is passing to it a Tournament
object. 因此,我有一个页面被加载,称为Tournament
tournament/:key
,它正在向其传递一个Tournament
对象。 As you can see from below the Jade template is accessing each variable from the Tournament
by using, for example, #{tournemantData.name}
which would print the Tournament
's name
to the page. 正如您从下面看到的那样,Jade模板正在通过使用#{tournemantData.name}
来访问Tournament
的每个变量,该变量会将Tournament
的name
打印到页面上。 The set of matches
is actually stored as an array within Tournament
, and I would like to access these through a JavaScript file in order to work with them on this page, as eventually I would like a set of graphical brackets to be produced. 这组matches
实际上存储为Tournament
一个数组,我想通过JavaScript文件访问这些matches
,以便在此页面上使用它们,因为最终我希望生成一组图形括号。
How would I access this tournamentData
inside a JavaScript file? 我将如何在JavaScript文件中访问tournamentData
数据?
app.get('/tournament/:key', function(req, res) {
util.log('Serving request for url [GET] ' + req.route.path);
Tournament.findByKey(req.params.key, function(err, tournamentData){
if(!err && tournamentData){
tournamentData = tournamentData;
//util.log(tournamentData.teams[0]);
res.render('tournamentDetails', { 'tournamentData' : tournamentData, seedsSerialized : JSON.stringify(tournamentData.teams) } );
} else {
util.log('Error in fetching Tournament by key : ' + req.params.key);
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Tournament by key ' + req.params.key
});
}
});
});
Jade: 玉:
p Name: #{tournamentData.name}
p ID: #{tournamentData._id}
p Key: #{tournamentData.key}
p Teams: #{tournamentData.teams}
p Matches: #{tournamentData.matches}
p Brackets:
div.bracket
#tournamentBrackets
script(type='text/javascript')
var seeds = var rankArray = !{seedsSerialized};
brackets.js brackets.js
numRounds = Math.log(seeds.length) / Math.log(2);
/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
*/
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
shuffleArray(seeds);
var bracketData = {
teams : [ // Matchups
[ seeds[0].name, seeds[1].name ],
[ seeds[2].name, seeds[3].name ]
],
results : [[
[ [1, 0], [1, 0] ],
[ [1, 0], [1, 0] ]
]]
}
$(function() {
$('#tournamentBrackets').bracket({
init: bracketData
});
});
EDIT: I have added the JavaScript file, what this is doing is using jQuery.bracket (a jQuery project I am using for generating nice looking brackets), at the moment you can see that I have manually put in the names of the teams. 编辑:我已经添加了JavaScript文件,这是使用jQuery.bracket(我正在使用jQuery项目生成美观的方括号),此刻您可以看到我已经手动输入了团队名称。
The array of brackets inside brackets.js
is the same format as in tournamentData.matches
, but the basic idea is that I want to access this information from within this JavaScript file so that I can print the brackets with these teams. 括号内的阵列brackets.js
是相同的格式tournamentData.matches
,但基本的想法是,我想从这个JavaScript文件中获取此信息,以便我可以打印与这些球队的支架。
Edit: 编辑:
$(document).ready(function() {
// tournament is now the same as tournmentData in your express route
var tournamentText = $(#tournamentData).text();
var tournament = JSON.parse(tournamentText);
console.log(tournament, tournament);
$(function() {
$('#tournamentBrackets').bracket({
init: bracketData
});
});
}
You can already access the variable in your Jade template meaning that you can access it in that page through Javascript. 您已经可以在Jade模板中访问变量,这意味着您可以通过Javascript在该页面中访问它。
Basically you already have the access to tournamentData object. 基本上,您已经可以访问TournamentData对象。
What you can do is get that tournamentData object and make it global JS variable or keep it in page scope. 您可以做的就是获取TournamentData对象并将其设置为全局JS变量或将其保留在页面范围内。
Something like this in your template 模板中的内容类似
- var matches = tournamentData.matches ; //Specific scope
Or 要么
- window.matches = tournamentData.matches; //Binded to window object global
You could publish your data on your Express server via a route like you've already shown with /tournament/:key
. 您可以通过/tournament/:key
所示的路线将数据发布到Express服务器上。
Something like : 就像是 :
app.get('/tournament-seeds/:key', function(req, res) {
Tournament.findByKey(req.params.key, function(err, tournamentData){
res.json({ tournamentData: tournamentData });
});
});
Then ... 然后 ...
In your brackets.js file you want to make a call to fetch your seeds (?) data: 您要在方括号.js文件中调用以获取种子(?)数据:
So changing your last function in brackets.js in your existing code to something like this (cut for brevity) should do what you want: 因此,将现有代码中的括号.js中的最后一个函数更改为以下内容(为简便起见,请按照以下说明操作)即可:
$(function() { $.get('/tournament-seeds/somerandomkey', function(tournamentData){
seeds = tournamentData.seeds;
$('#tournamentBrackets').bracket({
init: bracketData
});
});
});
Disclaimer: I'm not suggesting this is the best way to do it, it's the quickest I can think of at the moment! 免责声明:我并不是说这是最好的方法,这是我目前能想到的最快的方法!
Alternatively you could blat the json into a variable directly in your template. 或者,您可以直接在模板中将json放入变量中。 See: Passing an array to a JSON object for Jade rendering 请参阅: 将数组传递给JSON对象以进行Jade渲染
On your route: 在您的路线上:
app.get('/tournament/:key', function(req, res) {
util.log('Serving request for url [GET] ' + req.route.path);
Tournament.findByKey(req.params.key, function(err, tournamentData){
tournamentData = tournamentData;
util.log(tournamentData.teams[0]);
res.render('tournamentDetails', { 'tournamentData' : tournamentData, seedsSerialized : JSON.stringify(tournamentData.seeds) } );
});
});
In your jade template: 在您的翡翠模板中:
script(type='text/javascript')
var seeds = !{JSON.stringify(tournamentData.teams)};
In your brakets.js REMOVE your var seeds line. 在您的akets.js中,删除您的var种子行。
Not tested but it should get you going. 未经测试,但它应该可以帮助您。
When you say "JavaScript file" I am assuming you mean a client-side javascript file and not a server-side file in Express. 当您说“ JavaScript文件”时,我假设您是指Express中的客户端javascript文件,而不是服务器端文件。
Embedding your tournament data as a JSON string in the templtae 将您的锦标赛数据作为JSON字符串嵌入到templtae中
div(style="visibility: hidden")#tournamentData
!{JSON.stringify(tournamentData)}
Now in your in your client-side javascript you can access the text inside the #tournamentData div 现在,在您的客户端javascript中,您可以访问#tournamentData div中的文本
$(document).ready(function() {
// tournament is now the same as tournmentData in your express route
var tournamentText = $(#tournamentData).text()
var tournament = JSON.parse(tournamentText)
console.log(tournament, tournament)
$('#tournamentBrackets').bracket({
init: bracketData
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.