简体   繁体   English

从 Javascript 文件而不是 HTML/CSS 中检索变量值

[英]Retrieving variable values from Javascript file rather than HTML/CSS

I apologize if this is a simple issue but I've spent a long time being completely stuck, all guides are retrieving from the HTML file, and as such I have no clue where to even begin or what to search.如果这是一个简单的问题,我深表歉意,但我已经花了很长时间完全陷入困境,所有指南都从 HTML 文件中检索,因此我什至不知道从哪里开始或搜索什么。

        <form class="container" method="post">
            <div class="form-group">
                <input class="form-control" name="title">
            </div>
            <textarea class="form-control" name="content"></textarea>
            <button>add to mongodb</button>
        </form>

From this code in the HTML file, I can retrieve the values inputted,从 HTML 文件中的这段代码中,我可以检索输入的值,

app.post("/", function(req, res) {
    let newGameData = new gameData ({
        score: req.body.title,
        jumps: req.body.content,
    });
    newGameData.save();
    res.redirect('/')
})

However, instead of retrieving values from HTML forms, I want to retrieve variables from a game inside the HTML, the javascript file containing the below但是,我不想从 HTML forms 中检索值,而是想从 HTML 内的游戏中检索变量,ZDE9B9ED78D7E2E1ZEFFEE7 文件包含以下内容

var score = [];
var jumps = [];

These variables are appended to as the score increases and as the character jumps, at the end of each life, I want to append it to the score, and periodically retrieve this data to be uploaded onto MongoDB, and vice versa I retrieve and display the highscore.这些变量随着分数的增加和角色的跳跃而附加,在每个生命结束时,我想将 append 它添加到分数,并定期检索此数据以上传到 MongoDB,反之亦然我检索并显示高分。

I was thinking to write to a json file that could be uploaded onto MongoDB, though I have no clue how to go about it or if it's valid at all, any help would be greatly appreciated, thank you!我正在考虑写一个 json 文件,该文件可以上传到 MongoDB,尽管我不知道如何 go 关于它,或者如果它完全有效,任何帮助将不胜感激!

As suggested in the comments, learn about Ajax.正如评论中所建议的,了解 Ajax。 This is a sample code:这是一个示例代码:

 let newGameData = { score: title, jumps: content, }; $.post("/", newGameData, function(result) { console.log(result) })

and on the server side, don't redirect, but rather res.send(result).在服务器端,不要重定向,而是 res.send(result)。

You need to add type =submit in your button tag add to mongodb您需要在按钮标签中添加 type =submit 添加到 mongodb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM