如何将HTML的VAR放入nodejs文档中



我有一个带有用户输入的HTML,我希望将该输入转移到nodejs文档中。

html代码:

<script type="text/javascript">
              function redirect() {
                const name = document.getElementById("field").value;
              }
            </script>
<form action="stats.html">
                <input id="field" type="text" name="name" placeholder="Player Name...">
                <input id="button" type="submit" value="SEARCH" onclick="redirect()">
            </form>

和文档位于

index.js

public/index.html

尝试此

 <script type="text/javascript">
              var field;
              function onload(){
               field = document.getElementById("field")
         }
       function redirect() {
                var name = field.value;
              }
            </script>
<form action="stats.html" onload="onload()">
                <input id="field" type="text" name="name" placeholder="Player Name...">
                <input id="button" type="submit" value="SEARCH" onclick="redirect()">
            </form>

您必须在节点服务器中定义路由

app.post('/mydata',function(req,res) {
  let data = req.body.name;
   console.log(name);
});`

并将AJAX请求从您的Redirect()方法发送到此路线:

function redirect() {       
   const name = document.getElementById("field").value;       
  $.ajax({
    type: "POST",
    url: '/mydata',
    data: {name:JSON.stringify(name)},
    success: success
});

最新更新