【问题标题】:How to pass data from a node js file to an html file如何将数据从节点 js 文件传递​​到 html 文件
【发布时间】:2018-10-15 21:35:29
【问题描述】:

在 html 中,我使用 form 标记以 post 形式将值传递给节点 js 文件。

我在服务器端用html传入的值创建了一个新值。

我想将该值重新插入到 html 上的 textbox(result) 中。 我希望这个过程发生在同一页面上。

我正在用pug模板引擎编写html,路由器名称是form。

form(action='form' method='post')
            p.lead
                textarea(style='resize:none; width:400px; height:300px;' name='description' onkeydown="if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;return false;}") #include<stdio.h>&#10;int main()&#10;{&#10;&#10;    return 0;&#10;}
            p
                input(type='text' style='resize:none; width:400px; height:50px;' name='result' readonly='readonly')
            p
                input(type='submit' value='submit' class='btn btn-success')

html文件就是这样创建的,并且正在使用post方法将这些值发送到服务器。

app.post('/form',function(req,res) {
var description = req.body.description;
var source = description.split(/\r\n|\r\n/).join("\n");

fs.writeFile(file,source,'utf8',function(error) {
    console.log('write end');
});
var compile = spawn('gcc',[file]);
compile.stdout.on('data',function(data) {
    console.log('stdout: '+data);
});
compile.stderr.on('data',function(data){
    console.log(String(data));
});
compile.on('close',function(data){
    if(data ==0) {
        var run = spawn('./a.out',[]);
        run.stdout.on('data',function(output){
            console.log('end');
        });
        run.stderr.on('data', function (output) {
        console.log(String(output));
        });
        run.on('close', function (output) {
        console.log('stdout: ' + output);
        });
        models.Code.create( {
            title: 'test1',
            code: source 
        })
        .catch(err => {
            console.error(err);
        });
    }
  });
});

这是代码的post部分的摘录。

我已经成功在服务器端编译了htmltextarea写的值并提取结果。

但我不知道如何将值发送回 html。

【问题讨论】:

    标签: javascript html node.js post


    【解决方案1】:

    您可以使用 express js 中间件从 node.js 服务器 tk 所有视图传递数据 像这样

    app.use(function(req,res,next){
    res.locals.yourvariable = req.yourvariable;
    next();
    });
    

    希望对你有帮助

    【讨论】:

    • 经过搜索,我认为使用ajax比较合适,我正在研究那部分。谢谢。
    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 2021-06-25
    • 2020-10-29
    • 2021-08-07
    • 2020-05-31
    • 2019-01-11
    • 1970-01-01
    • 2012-02-12
    相关资源
    最近更新 更多