Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - how to set value of text field in html from nodejs?

I'm doing project in nodejs and html .can anybody help how to set value to text field in html from server.js. For example I've text field with id 'name' on index.html. i use res.body.name = 'nametest' .but its not working .please give me a simple example . Thank you friends

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to set a field from the server, you want to make it a preset value which you define when sending the HTML or you want to set it dynamically later on. The first option is easy, the second one a bit advanced.

Let's look at option 1. This is just a very basic example! Please don't use this in production.

index.html

<!DOCTYPE html>
<html>
  <head><!-- your stuff here --></head>
  <body><input type="text" name="someVal" value="{{someVal}}"></body>
</html>

This might be your HTML. Just but a distinctive placeholder where you want your value to go. There might be better techniques out there to do this, but for the sake of simplicity I chose this way.

server.js

var http = require('http');
var fs = require('fs');

http.createServer((req, res) => {
  fs.readFile('index.html', (err, data) => {
    if (err) {
      res.writeHead(500);
      res.end(err);
      return;
    }

    data = data.toString().replace(/{{someVal}}/, 'your value here');
    res.writeHead(200);
    res.end(data, 'utf8');
  });
}).listen(8080);

This server.js will open a HTTP server on port 8080. It will try to read index.html from the same directory. If it fails, it will send the error message to the client, else it will replace your placeholder in your HTML with your value and then send the modified content to the client.
If that's all you want to do, PHP might do a better job for you (but that's just my 2 cents :) )

Option 2 is a lot more elaborate. You would have to either use AJAJ (Asynchronous Javascript and JSON) which requires the client to know when to fetch the value or you could make use of websockets which enable the server to push a value to the client. For either of those there are a lot of tutorials out there which are a lot more detailed than anything I could put together for you here.
If you want to use those techniques, but are a bit unsure about their iomplementation, you might want to look at frameworks like Meteor and Socket.IO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...