【发布时间】:2018-06-10 09:16:21
【问题描述】:
我正在创建一个两人游戏,其中玩家有 10 次尝试猜测一个单词。我需要在不刷新整个页面的情况下将他的猜测和分数放在一张桌子上。问题是我只知道如何使路由成为只重定向到另一个 url 的快捷方式。我正在寻找婴儿术语的分解,以便将来可以将其应用于其他项目。关于这个问题的所有其他帖子都没有教如何合并快速代码等,也没有分解它。
这里是 express/nodejs 代码
router.get( "/arena", function ( req, res, next){
res.render('arena', {Title:"Arena"});
})
router.post( "/arena", function ( req, res, next){
if( req.body.matchTitle && req.body.newGuess && req.body.newGuess.length == 5){
var newGuess = req.body.newGuess;
var oldGuesses = req.body.oldGuess; //an array of the previously guessed words
//verify this word is found in the dictionary
var res = loadDicCompare(newGuess); //returns true or false
//Give the guess a score
var score = Score(newGuess);
//save new Guess to the database
Game.findAndUpdate( { matchTitle : req.body.matchTitle } , { $push : { guess : newGuess } } , function (){
if( err ) {
return next(err)
}
else {
res.render('arena', {Title:"Arena", Score : score, Guess: newGuess, pastGuesses : oldGuesses});
}
})
}
else{
res.render('arena', {Title:"Arena", Alert : "Sorry insufficient data"});
}
})
这是我的哈巴狗模板(它必须将所有旧猜测和他们的分数加载回表中加上最近的猜测,然后它必须添加一个新的表格行,其中包含新猜测的输入字段):
extend layout
block content
h2.h2WithTable #{Gid}Stacy vs. Kelly#{cGid}
form( method = 'POST' action = '/arena' )
table#gameTable
if ( Alert)
- alert('Alert')
else
if pastGuesses
each word, ind in pastGuesses
tr.hideme( type = 'text' maxlength=5 name = 'oldGuess' )
tr.hideme( type = 'text' maxlength=5 name = 'oldScore' )
tr
td #{word[0]}
td #{word[1]}
td #{word[2]}
td #{word[3]}
td #{word[4]}
td #{pastScores[ind]}
if newGuess
tr
td #{newGuess[0]}
td #{newGuess[1]}
td #{newGuess[2]}
td #{newGuess[3]}
td #{newGuess[4]}
td #{Score}
tr
td
input#newGuess( type = 'text' maxlength=5 name = 'newGuess' )
td.wide
button#send( type = 'submit' ) Try
使用此代码,它使页面一遍又一遍地重新加载页眉、导航、表格、所有表格数据和页脚,直到游戏结束。这就是我想要发生的事情
- 获取 newGuess(仅限)
- 给newGuess打分(我做了一个计分功能)
- 在表格中添加一行,单词的每个字母在一列(5 个字母),分数在最后一列
- 在第一列添加另一个带有输入字段的新行,在最后一列添加提交按钮
【问题讨论】:
-
可以使用ajax
标签: javascript node.js ajax mongodb express