【问题标题】:How can i store the text from a html input field in a node.js variable?如何将来自 html 输入字段的文本存储在 node.js 变量中?
【发布时间】:2018-05-31 15:45:46
【问题描述】:

我的 node.js 代码如下所示:

var connect = require('connect'); 
var serveStatic = require('serve-static'); 

connect().use(serveStatic("WebDir")).listen(80, function(){ 
    console.log('Server running on port 80...'); 
});

我想使用 API 并使用 node.js 中输入字段中的数据 我该怎么做。 Input 字段只是 HTML 中的普通输入字段

【问题讨论】:

  • 请显示您要存储的位置。
  • 类似 var username = textfield.innerHTML 或类似的东西
  • 在 jQuery 中你可以使用 var inp = $("#example").val(); 来完成,让我查找 JS。
  • var test = document.getElementById('getInput').value; 这是给 JS 的

标签: javascript html css node.js


【解决方案1】:

您可以使用 Node.js Express 为此创建一个简单的测试设置。

2 个文件:index.js、index.html

index.html

<html>
<head>
      <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
      <script type="text/javascript">

        var sendInput = function() {
            var inputField = $('#inputField').val();

            console.log(inputField);

            $.ajax({
                type: 'POST',
                url:  'http://localhost:3000/inputData',
                crossDomain: true,
                data: JSON.stringify({ inputField: inputField }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result, status){
                    document.getElementById("output").innerHTML = result.nodeVariable;
                },
                error: function (errorMessage) {
                    console.error('Error: ', errorMessage);
                }
            });
        }

      </script>
</head>
<body topmargin="40" leftmargin="40">
 <div id="result">Loading..</div>
 </br>
 <button onClick="sendInput()">Send input to Node.js</button> : <input type="text" id="inputField" value="test value"><br>
 <div>
 <br/>Result: <p id="output"></p>
 <div>
 </body>
</html>

服务器端,这是 node.js 脚本。

index.js

const bodyParser = require('body-parser');
const express = require('express');
const port = (process.env.PORT || 3000);

const app = express();

app.use(express.static(__dirname));
app.use(bodyParser.json());

app.post('/inputData', (req, res, next) => {

    console.log('/inputData post: ', JSON.stringify(req.body));
    // Read the variable..
    var inputField = req.body.inputField;
    console.log('Input field: ', inputField);

    res.status(201).send(JSON.stringify({status: 'OK',  nodeVariable: inputField + " - updated by node."}))
});

app.listen(port);
console.log('Express listening on port ' + port);

在浏览器上转到http://localhost:3000 进行测试。

【讨论】:

  • 感谢您的精彩回答。我会在我在家时测试它是否有效。已经谢谢你了
  • 如何更改节点中html标签的值?
  • 我已经更新了我的答案以显示从节点变量修改 HTML。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2013-05-12
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 2014-11-09
  • 2012-11-25
相关资源
最近更新 更多