[英]How can I take variable from ejs to app.js in Node.js?
我是node.js的新手,试图将JSON数据从ejs传递到app.js,但我不知道如何从ejs传递到app.js。
我所做的是var stringify1 = <%- JSON.stringify(jsonfile_1) %>;
从ejs中
然后在用户单击“保存”按钮后,使其转到'/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中找到但找不到所需的解决方案。
有人对此有想法吗?
提前致谢。
PS与上面的代码,它给了我一个错误,即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);
});
最好将json内容放在表单内的隐藏字段中,并在单击saveImage链接时提交表单。
<form action="/save" id="hdnJsonForm" method="POST">
<input type="hidden" name="json1" id="jsonjson">
</form>
在javascript中,单击保存链接时必须提交表单。 如果使用JQuery,则可以实现此目的。
$(document).on('click','#imageSave',function(){
$('#hdnJsonForm').submit();
});
接下来,您要做的就是更改发布路线
app.post('/save', isLoggedIn, function(req, res){
console.log(stringify1);
});
希望能帮助到你!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.