首页 > 解决方案 > 涉及DOM时如何在多个文件之间传输变量?

问题描述

我正在尝试将一些数据存储到mysql中。流程是这样的:首先,在我table.js生成如下表。

function tableBody() {
let tr; //table <tr>
let td; //table <td>
let tblBodyContent = document.getElementById('tableBodyContent');
for (let i = 0; i < 10; i++) {
    tr = document.createElement('tr')
    for (let col = 0; col < 6; col++) { 
        if (col === 5 && i > 5) break; 
        td = document.createElement('td')
        td.innerHTML = 'cell value here';
        let cellID = Math.floor(Math.random() * 100);
        td.setAttribute('id', cellID);
        td.addEventListener('click', cellClick);
        tr.appendChild(td)
    }
    tblBodyContent.appendChild(tr);
}}
function cellClick() {
   let tableCellId = this.id;
   window.open("./form.html")}

表格中的每个单元格都是可点击的,当一个单元格被点击时,它会打开form.htmlform.html代码如下:

  <body>
      <div class="container">
        <div id="test">
          <p>desplay the cellID</p>
        </div>
            <form action="user_input" method="POST">
                <label for="inputname">Name</label>
                    <div class="form-group col-md-6">
                      <input type="name" class="form-control" id="inputfistname" name="inputfistname" placeholder="Firstname">
                    </div>
                  <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </div></body>

单击提交按钮时,我想将两条数据存储到mySql中,代码storeData.js如下:

const mysql = require('mysql');
const express = require('express');
const morgan = require('morgan');
const { prohairesis } = require('prohairesis');
const bodyParser = require('body-parser');
const mysqlConnect = require('./mysqlConnect')

const app = new express();
const port = process.env.PORT || 8000;
app
.use(morgan('short'))
.use(bodyParser.urlencoded({ extended: false }))
.use(express.static('./'))

.post('/user_input', (req, res) => {
    const cellId = ''; //I'm stucked here: tableCellId from test.js
    const firstName = req.body.inputfistname;

    const queryString = 'INSERT INTO userinfo VALUE (?,?)';
    mysqlConnect.connection.query(queryString, [firstName, cellId], (err, rows, fields) => {
        if (err) {
            console.log(`the error is ${err}`)
            res.send(500);
            throw err;
        }
    })
})
.listen(port, () => {
    console.log(`server listening on port ${port}`)
})

我被困在这里,因为一个数据是在cellClick 函数中cellId生成的随机数,因为我包含 DOM 元素,所以我不能在我的中使用,有没有办法可以从我的中调用这个变量?那么我可以将它存储在mySql中吗?table.jstableCellIdtable.jsrequire('./table.js')storeData.jstable.jsstoreData.js

标签: javascriptnode.jsexpress

解决方案


是的。使用本地存储。首先,像这样设置你的 cellClick 函数:

function cellClick() {
   let tableCellId = this.id;
   window.localStorage.setItem('cell_id', tableCellId);
   window.open("./form.html")
}

稍后,当 form.html 被加载时。将 LocalStorage cell_id 中的值加载到隐藏输入中。

<form action="user_input" method="POST">
  <label for="inputname">Name</label>
  <div class="form-group col-md-6">
    <input type="name" class="form-control" id="inputfistname" name="inputfistname" placeholder="Firstname">
    <input type="hidden" name="input_cell_id" value="">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

<script>
  document.querySelector('input[name="input_cell_id"]').value = window.localStorage.getItem('cell_id');
</script>

在您的 node.js 中,您以与名字相同的方式获取值。

const cellId = req.body.input_cell_id;

推荐阅读