简体   繁体   中英

Sending data from JS file to HTML page

I am new to NodeJS. Here is the simple program to send data back and forth from HTML to NodeJS files. My index.html contains a form and div to display the reply received back from server.js:

<html>
<body>

    <form action = "http://127.0.0.1:8000/process_post" method = "POST">
        First Name: <input type = "text" name = "first_name">  <br>
        Last Name: <input type = "text" name = "last_name">  <br>
        <input type = "submit" value = "Submit">
    </form>
    <div><%= name %></div>
</body>
</html>

Below is the code for server.js:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(urlencodedParser);

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.post('/process_post', function (req, res) {
    var name = req.body.first_name+ ' ' + req.body.last_name;   //to send back to HTML
    console.log(name);
    res.send(name);
 });

var server = app.listen(8000);

How to update the name in HTML page with the value of name in JS program, each time the form is submitted?

You can use AJAX (fetch or Axios for example). Create an event listener on your submit input with a function like this:

 axios.post('/process_post', { first_name: 'Fred', last_name: 'Flintstone' }) .then(response => { document.querySelector('div').textContent = response; }) .catch(error => { console.log(error); });

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