如何从服务器端nodejs访问客户端javascript变量?

时间:2015-01-08 12:11:51

标签: javascript node.js express

我想访问变量" content"从服务器端到客户端,我该怎么做?

extends layout

block content
div(id="ineditortxt")
    h1(name="headings") #{title}
    a(href='/signout', class='text-center new-account') Sign Out
    div(id="editor")
        |public class #{title}{
        |   public static void main(String[] args) {
        |   
        |   }
        |}
    script(src="src/ace.js", type="text/javascript")
    script(type="text/javascript").
            var editor=ace.edit("editor");
            editor.setTheme("ace/theme/monokai");
            editor.getSession().setMode("ace/mode/java");
            function getText(){
                event.preventDefault();
                var content = editor.getValue();
                return false;
            }
    form(name="Save", id = "save", onsubmit="getText()")
        input(type="submit", value="Save")

1 个答案:

答案 0 :(得分:0)

这取决于您要为应用程序使用的协议。

如果您使用经典的http并且在节点中运行快速(http)服务器,则应遵循this post中所述的内容。您的客户端正在向服务器发送http-post请求,这样您就可以从html表单访问变量。在纯HTML中,表单看起来像这样:

<form action="/save" method="post">
<input id="save" type="text" />
<input type="submit" value="Save" />
</form>

您使用express在服务器端捕获的URL将是http://your-page.com/save

app.post('/save', function(req, res) { ...

你也可以使用&#34;现代&#34; WebSocket protocol,客户端和服务器可以相互自然地说话#34}。但这也很新,并不总是很容易集成到现有的http-infrastructur。 对于websocket,您可以使用模块:socket.io作为节点,也可以与快速http服务器结合使用。

然后看起来像这样:

var express = require('express'),
    app = express(),
    server = require('http').Server(app),
    // Implementation of the WebSocket protocol.
    io = require('socket.io')(server);
server.listen(3000); // port your server is listening, test with localhost:3000

io.on('connection', function (socket) {
  socket.on('save', function (content) {
    // do something with your content variable
  });
});

在客户端(使用jquery):

var socket = io();
$('#save').click(function () {
  socket.emit('save', content);
});

如果你决定使用websocket,我建议你看看这个简单chat implementation

相关问题