You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongo-Express-Node MVC架构下,View中JS变量如何传递至Controller

问题描述

我基于Mongo、Express、Node.js栈实现了MVC架构项目,View层包含:

  • 对应根路径/的index.html
  • 对应/test/example路径的create-form.html
  • 通用脚本main.js(在/页面中根据用户输入计算出points变量)

需求是将计算得到的points传递至controllers/homepage.js中的module.exports.doCreate函数,该函数还需要接收create-form.html页面用户填写的age、xray字段,最终将这三个字段一同通过API存入MongoDB。

之前尝试在main.js中用jQuery实现:点击#req_api_but按钮时,通过GET请求获取/test/example页面,设置隐藏字段#points的值后跳转,但未成功。


文件结构

views/
├─ main.js
├─ index.html
├─ create-form.html
controllers/
├─ homepage.js

相关代码片段

controllers/homepage.js

...
module.exports.doCreate = function(req, res) {
    var postdata = {
        age: req.body.age,
        // points: points, // 需要传入这个变量
        xray: req.body.xray
    };
    console.log(postdata);
    axios.post('https://some.domain/api/users', postdata, {
        headers: {
            'Content-Type': 'application/json'
        }
    });
}
...

main.js(尝试的jQuery代码)

$("#req_api_but").on("click", function (e) {
    e.preventDefault();
    $.get('/test/example', function (data) {
        window.location.href = '/test/example';
        $(data).find('#points').text(points);
    });
});

解决方案

你之前的尝试失败是因为:跳转页面后,通过$(data)操作的临时DOM会被浏览器新页面完全替换,无法保留修改。下面提供三种可行的实现方式:

方法1:通过URL参数传递points(适合非敏感数据)

步骤1:修改main.js的跳转逻辑

直接把points拼到跳转URL的参数里:

$("#req_api_but").on("click", function (e) {
    e.preventDefault();
    // 用encodeURIComponent处理特殊字符,避免URL解析错误
    window.location.href = `/test/example?points=${encodeURIComponent(points)}`;
});

步骤2:修改create-form.html,添加隐藏字段并读取URL参数

在表单中加入隐藏字段,页面加载时从URL参数中取出points赋值:

<form action="/test/example/submit" method="POST">
    <!-- 原有表单字段:age、xray -->
    <input type="hidden" id="points" name="points" value="">
    <button type="submit">提交</button>
</form>

<script>
window.onload = function() {
    const urlParams = new URLSearchParams(window.location.search);
    const points = urlParams.get('points');
    if (points) {
        document.getElementById('points').value = points;
    }
};
</script>

步骤3:修改homepage.js的doCreate函数

表单提交时隐藏字段会被一起POST,直接从req.body中获取points:

module.exports.doCreate = function(req, res) {
    var postdata = {
        age: req.body.age,
        points: req.body.points, // 成功获取points
        xray: req.body.xray
    };
    console.log(postdata);
    axios.post('https://some.domain/api/users', postdata, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        // 处理成功逻辑,比如跳转至结果页
        res.redirect('/success');
    })
    .catch(error => {
        console.error(error);
        res.status(500).send('提交失败');
    });
}

方法2:通过Express Session存储points(适合敏感数据)

如果points是敏感数据,不适合暴露在URL中,可以用Session存储:

步骤1:配置Express Session

先安装依赖:

npm install express-session

在项目入口文件(如app.js)中添加Session配置:

const session = require('express-session');
app.use(session({
    secret: 'your-custom-secret-key', // 替换为你的私密密钥
    resave: false,
    saveUninitialized: true,
    cookie: { secure: false } // 生产环境建议开启HTTPS并设为true
}));

步骤2:新增路由接收points并存入Session

在路由文件(如routes/home.js)中添加:

router.post('/save-points', (req, res) => {
    req.session.points = req.body.points;
    res.sendStatus(200);
});

步骤3:修改main.js,先存Session再跳转

$("#req_api_but").on("click", function (e) {
    e.preventDefault();
    // 先把points传给后端存入Session
    $.post('/save-points', { points: points }, function() {
        window.location.href = '/test/example';
    });
});

步骤4:修改homepage.js的doCreate函数,从Session取points

module.exports.doCreate = function(req, res) {
    var postdata = {
        age: req.body.age,
        points: req.session.points, // 从Session获取points
        xray: req.body.xray
    };
    console.log(postdata);
    axios.post('https://some.domain/api/users', postdata, {
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        // 提交成功后清除Session中的points,避免重复使用
        delete req.session.points;
        res.redirect('/success');
    })
    .catch(error => {
        console.error(error);
        res.status(500).send('提交失败');
    });
}

方法3:通过LocalStorage传递(纯前端方案)

适合非敏感数据,无需后端额外开发:

步骤1:修改main.js,把points存入LocalStorage再跳转

$("#req_api_but").on("click", function (e) {
    e.preventDefault();
    localStorage.setItem('calculatedPoints', points);
    window.location.href = '/test/example';
});

步骤2:修改create-form.html,从LocalStorage取points赋值

<form action="/test/example/submit" method="POST">
    <input type="hidden" id="points" name="points" value="">
    <!-- 原有表单字段:age、xray -->
    <button type="submit">提交</button>
</form>

<script>
window.onload = function() {
    const points = localStorage.getItem('calculatedPoints');
    if (points) {
        document.getElementById('points').value = points;
        // 可选:取完后清除LocalStorage,避免数据残留
        localStorage.removeItem('calculatedPoints');
    }
};
</script>

步骤3:修改homepage.js的doCreate函数

和方法1一致,直接从req.body.points获取即可。


内容的提问来源于stack exchange,提问作者memooo24353

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 21:44:55