【发布时间】:2017-08-12 16:27:25
【问题描述】:
我是 node.js 的新手,正在尝试将 JSON 数据从 ejs 传递到 app.js 但我不知道如何从ejs传递到app.js。
我所做的是来自ejs的var stringify1 = <%- JSON.stringify(jsonfile_1) %>;,
然后在用户点击保存按钮后,让它转到'/save'
然后我使用 app.get 如下代码。
app.get('/save', isLoggedIn, function(req, res){
console.log(stringify1);
});
这是来自 ejs 的部分脚本代码,它生成 json 数据,然后转到app.get('/save',..
<script>
function save(){
var jsonfile_1 = {channel: {}};
for (i = 0; i < jsonfile.channel.length; i++){
var divData = document.getElementById(jsonfile.channel[i]);
var mac_tmp = jsonfile.channel[i];
if(divData.dataset.x != 0 && divData.dataset.y != 0){
jsonfile_1.channel[mac_tmp] = [divData.dataset.x, divData.dataset.y];
}
}
console.log(jsonfile_1.channel);
console.log(JSON.stringify(jsonfile_1));
var stringify1 = <%- JSON.stringify(jsonfile_1) %>;
saveText(JSON.stringify(jsonfile_1.channel), "hello.json");
}
</script>
这是我的按钮代码
<a onclick= "save()" id="imageSave" href="/save">Save</a>
我尝试在 google 中查找,但找不到我想要的解决方案。
有人对此有什么想法吗?
提前致谢。
P.S 上面的代码给了我一个 jsonfile_1 未定义的错误。
编辑
<script>
function save(){
var jsonfile_1 = {channel: {}};
for (i = 0; i < jsonfile.channel.length; i++){
var divData = document.getElementById(jsonfile.channel[i]);
var mac_tmp = jsonfile.channel[i];
if(divData.dataset.x != 0 && divData.dataset.y != 0){
jsonfile_1.channel[mac_tmp] = [divData.dataset.x, divData.dataset.y];
}
}
console.log(jsonfile_1.channel);
console.log(JSON.stringify(jsonfile_1));
document.getElementById("jsonjson").value = JSON.stringify(jsonfile_1.channel);
saveText(JSON.stringify(jsonfile_1.channel), "hello.json");
}
function saveText(text, filename){
var a = document.createElement('a');
a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text));
a.setAttribute('download', filename);
a.click()
}
</script>
保存按钮
<li><a onclick= "save()" id="imageSave" href="/save">Save</a></li>
app.js
app.get('/save', isLoggedIn, function(req, res){
console.log(req.body.json1);
});
【问题讨论】:
-
在服务器端,你有 req 和 res 对象可用。因此,您可以使用它们来获取数据。在客户端,您可以将数据放在一些隐藏的 div 元素中,并尝试使用 req.body.name 将它们获取到服务器中,您可以搜索更多关于如何在服务器中获取 req 参数..
-
你能提供更多代码吗,它似乎不完整,也不清楚你想要实现什么。我相信
saveText(JSON.stringify(jsonfile_1.channel), "hello.json");会进行 Ajax 调用,因此您可以获取像req.query.param_name这样的参数 -
@SarojSasmal 等我编辑
-
@SarojSasmal 我编辑了它..请在这里帮帮我.... :'(
-
@SarojSasmal 我认为您的第一条评论是正确的方式。您能否更具体地说明代码? :'(
标签: javascript json node.js ejs