简体   繁体   中英

How to accessing client side javascript variable from server side nodejs?

I want to access the variable "content" on to the client side from the server side, how would I do this?

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")

This dependes on what protocol you want to use for your application.

If you use classical http and you run an express (http) server in node, you should follow something as described in this post . Your client is sending a http-post request to the server, like this you can access a variable from a html form. In pure html the form looks something like this:

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

The URL you would catch on the server side using express would be http://your-page.com/save

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

You can also use the "modern" WebSocket protocol , where client and server can "speak a bit more naturally with each other" but which is also quite new and not always easy to integrate to the existing http-infrastructur. For websocket you can use the module: socket.io for node, also in combination with an express http server.

Then it would look like something like this:

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
  });
});

And on the client side (using jquery):

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

If you decide to use websocket, I would recommend you to look at this easy chat implementation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM