首页 > 解决方案 > 如何从 JavaScript 变量中检索多个值并将其传递给 Node JS?

问题描述

脚本

这是我在 HTML 文件底部的 Javascript 脚本:

var savedValues = []
var currentId = document.getElementById("fridgeFreezer").value

function handleChange() {
// The new values for the fridge with id currentId:
var temp = document.getElementById("temperature").value
var comments = document.getElementById("comments").value

// Save these values for the previous id
// - First, check to see if we already have a record we can update
var save = savedValues.find(save => {
  return save.id === currentId
})
// - If we do, update it, otherwise create a new record
if (save) {
  save.temp = temp
  save.comments = comments
} else {
  savedValues.push({
    id: currentId,
    temp: temp,
    comments: comments,
  })
}

// Update the current id to the newly selected option
currentId = document.getElementById("fridgeFreezer").value

这是 Google Chrome 控制台上的输出

{…}]
0: {id: "Fridge 1", temp: "", comments: ""}
1: {id: "Fridge 2", temp: "3", comments: "a"}
length: 2
__proto__: Array(0)

节点JS

我有一个控制器

exports.getData = async function(req, res) {
  var {savedValues} = req.body;
  console.log(savedValues);
}

细节

这目前没有任何作用。

问题

如何从 JavaScript 脚本中获取任何变量并在 Node JS 中使用它?

目标:

我的目标是从 JavaScript 脚本中获取值以在 Node JS 中使用以插入 MySQL 数据库。

完整的 HTML 代码

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    <link rel="stylesheet" href="/style.css">
  </head>
  <body>

    <nav>
      <h4>Technical</h4>
      <ul>
        <li><a href="/">Home</a></li>
          {{#if user}}
          <li><a href="/profile">Profile</a></li>
          <li><a href="/auth/logout">Logout</a></li>


        {{else}}
          <li><a href="/login">Login</a></li>
          <li><a href="/Register">Register</a></li>
        {{/if}}
      </ul>
    </nav>

    <div class="container mt-4">
      <h1 class="text-left" style="margin-bottom: 50px">Daily Fridge & Freezer Monitoring Record</h1>
        <form action="/auth/21-TEMP-01b" method="post">
          <div class="form-group">
            <label>Select Fridge Or Freezer</label>
            <select class="form-control" id="fridgeFreezer" name="fridge">
              <option value="Fridge 1">Fridge 1</option>
              <option value="Fridge 2">Fridge 2</option>
              <option value="Fridge 3">Fridge 3</option>
              <option value="Fridge 4">Fridge 4</option>
              <option value="Fridge 5">Fridge 5</option>
              <option value="Fridge 6">Fridge 6</option>
              <option value="Fridge 7">Fridge 7</option>
              <option value="Fridge 8">Fridge 8</option>
              <option value="Fridge 9">Fridge 9</option>
              <option value="Fridge 10">Fridge 10</option>
              <option value="Freezer 1">Freezer 1</option>
              <option value="Freezer 2">Freezer 2</option>
              <option value="Freezer 3">Freezer 3</option>
              <option value="Freezer 4">Freezer 4</option>
              <option value="Freezer 5">Freezer 5</option>
            </select>
          </div>

          <div class="form-group">
            <label>Temperature °C</label>
            <input class="form-control" type="number" id="temperature" name="temperature">
          </div>

          <div class="form-group">
            <label>Comments</label>
            <textarea class="form-control" rows="3" id="comments" name="comments"></textarea>
          </div>

          <button type="submit" class="btn btn-primary">Submit</button>
        </form>



  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
  <script type="text/javascript">

var savedValues = []
var currentId = document.getElementById("fridgeFreezer").value

function handleChange() {
// The new values for the fridge with id currentId:
var temp = document.getElementById("temperature").value
var comments = document.getElementById("comments").value

// Save these values for the previous id
// - First, check to see if we already have a record we can update
var save = savedValues.find(save => {
  return save.id === currentId
})
// - If we do, update it, otherwise create a new record
if (save) {
  save.temp = temp
  save.comments = comments
} else {
  savedValues.push({
    id: currentId,
    temp: temp,
    comments: comments,
  })
}

// Update the current id to the newly selected option
currentId = document.getElementById("fridgeFreezer").value

// Load any previously saved data for this new id
save = savedValues.find(save => {
  return save.id === currentId
})
// If we find a previous value, load it, otherwise empty the inputs
if (save) {
  document.getElementById("temperature").value = save.temp
  document.getElementById("comments").value = save.comments
} else {
  document.getElementById("temperature").value = ''
  document.getElementById("comments").value = ''
}

console.log(savedValues);

}

// Attach the event listener to the document
document.getElementById("fridgeFreezer").addEventListener('change', handleChange, false);


  </script>
  </body>
</html>

标签: javascriptnode.js

解决方案


您可以简单地在您的路线中创建一条路线,node.js然后在您提交表单时从您的 javascript 中对路线进行后期调用

const form = document.getElementById('user-form') //give your form an id
form.addEventListener('submit', submitform, false) //add event listener 
var submitform = function sbmform(e) {
  e.preventDefault() // prevent submission
  submitvalues() // exec function 
}
var savedValues = []

function submitvalues() {
  var currentId = document.getElementById("fridgeFreezer").value
  // The new values for the fridge with id currentId:
  var temp = document.getElementById("temperature").value
  var comments = document.getElementById("comments").value

  // Save these values for the previous id
  // - First, check to see if we already have a record we can update
  var save = savedValues.find(save => {
    return save.id === currentId
  })
  // - If we do, update it, otherwise create a new record
  if (save) {
    save.temp = temp
    save.comments = comments
  } else {
    savedValues.push({
      id: currentId,
      temp: temp,
      comments: comments,
    })
  }

  // Update the current id to the newly selected option
  currentId = document.getElementById("fridgeFreezer").value

  data = {
    data: savedValues
  }
  // make an call to submit the values 
  fetchobj = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  }
  url = "your route url"
  fetch(url, fetchobj)
  form.removeEventListener('submit', submitform, false);
  form.submit()

}

推荐阅读