如何透過 DOM 而不是透過表格來呈現數據
P粉207483087
P粉207483087 2024-04-04 18:17:27
0
1
3785

我對我正在創建的應用程式有疑問,我正在使用Oracle 資料庫,並且我正在從資料庫中獲取資訊並透過表格將其呈現在螢幕上,但我想嘗試單獨處理這些數據,例如創建一個段落並顯示一個值。

我只能透過表格來呈現數據,還有其他方法嗎?如果有人能幫助我,非常感謝。

我接受所有改進程式碼的提示。

我的Index.html頁面

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Apontamentos da Produção</title>
  <link rel="stylesheet" type="text/css" href="styles.css" media="screen" />

</head>

<body>
  <meta http-equiv="refresh" content="5">

  <div id="data"></div>

  <div class="grid-container">
    <div class="container">
      <div class="texto"> PAINEL-1 | APONTAMENTOS DA PRODUÇÃO</div>
      <div class="clock"></div>
    </div>
  </div>
  <div class="progress">
    <div class="progress-bar"></div>
  </div>

  <br>

  <!-- Tabela principal, apresentando os apontamentos -->
  <table id="table" class="tablePrincipal">
    <tr class="trPrincipal">
      <th class="th2" style="width: 11%;">Data</th>
      <th class="th2" style="width: 8%; ">Hora</th>
      <th class="th2" style="width: 5%;">Orig.</th>
      <th class="th2" style="width: 8%;">O.P.</th>
      <th class="th2" style="width: 10%;">Produto</th>
      <th class="th2" style="width: 8%;">Deriv.</th>
      <th class="th2" style="width: 9%;">Peso (TN)</th>
      <th class="th2" style="width: 7%;">Refugo (TN)</th>
      <th class="th2" style="width: 13%;">Lote</th>
      <th class="th2" style="width: 60%;;">Operador</th>
    </tr>
  </table>

  <br>

</body>

<script>

// Tabela de apontamentos. Listagem.

  // Aqui é onde é feito o push de informações, chamando pelo caminho e colocando o ID da tabela que ele vai levar as informações

  window.onload = function () {
    fetch('http://localhost:3000/teste')
      .then(response => response.json())
      .then(data => {
        console.log(data);
        var table = document.getElementById('table');

        // Primeiro define a variavel, e coloca o comando para inserir uma linha, é tudo organizado por rows
        for (var i = 0; i < 7; i++) {
          var row = table.insertRow(i + 1);
          var cell1 = row.insertCell(0);
          var cell2 = row.insertCell(1);
          var cell3 = row.insertCell(2);
          var cell4 = row.insertCell(3);
          var cell5 = row.insertCell(4);
          var cell6 = row.insertCell(5);
          var cell7 = row.insertCell(6);
          var cell8 = row.insertCell(7);
          var cell9 = row.insertCell(8);
          var cell10 = row.insertCell(9);

          // Queria trabalhar com os dados separadamente, tentar criar um <p> e colocar um dado para apresentar.

        // Queria tentar fazer um calculo com essa variável, mas não funciona assim
          var cell11 = cell7 * 2;

          // Aqui chama a variavel e coloca a linha na tabela
          cell1.innerHTML = data[i][0];
          cell2.innerHTML = data[i][1];
          cell3.innerHTML = data[i][2];
          cell4.innerHTML = data[i][3];
          cell5.innerHTML = data[i][4];
          cell6.innerHTML = data[i][5];
          cell7.innerHTML = data[i][6];
          cell8.innerHTML = data[i][7];
          cell9.innerHTML = data[i][8];
          cell10.innerHTML = data[i][9];
        
        
        }}
      )}
      
</script>

</html>

這是我的Index.js,我在其中進行選擇並發送資料

const express = require('express');
const oracledb = require('oracledb');
const app = express();
var cors = require('cors')
app.use(cors())
const http = require('http');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');



// Connection details for the Oracle database
const connectionString = '';
const user = '';
const password = '';

// Connect to the database
app.get('/teste', (req, res) => {

  // within the endpoint, query the database
  oracledb.getConnection(
    {
      connectionString: connectionString,
      user: user,
      password: password
    },
    function teste(err, connection) {
      if (err) {
        console.error(err.message);
        return;
      }
      console.log('Conexão deu certo!');

      const query = 'SELECT DATREA,HORREA,CODORI,NUMORP,CODPRO,CODDER,QTDRE1,QTDRFG,CODLOT,OPERADOR from USU_VPROEXT ORDER BY DATREA DESC, HORREA DESC';
      connection.execute(query, [], (err, result) => {
        if (err) {
          console.error(err.message);
          return;
        }
        console.log('Banco de Dados Atualizado');
        console.log();

        // return the results to the user
        res.json(result.rows);
      });
    });
});

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

P粉207483087
P粉207483087

全部回覆(1)
P粉706038741

假設:

由於無法準確重現該場景,我將重點關注客戶端,只理所當然地認為您的後端端點將正確返回一個數組,例如:data[iRow][iColumn]

#這樣的假設來自這樣的行 cell1.innerHTML = data[i][0];

靜態定義的資料範例:

我不太確定資料是否只是數組的數組,或者是否有某種方法可以透過列名稱來尋址列值。無論如何,在這裡我們將堅持使用普通數組範例,因為它似乎按照您自己的話工作。

這裡我們定義了一個 data 數組,包含 2 行,每行 10 列:

//the array you are supposed to receive from your ajax call
const data = [
  //first row of cells
  [
    'rowX_cell(01)',
    'rowX_cell(02)',
    'rowX_cell(03)',
    'rowX_cell(04)',
    'rowX_cell(05)',
    'rowX_cell(06)',
    'rowX_cell(07)',
    'rowX_cell(08)',
    'rowX_cell(09)',
    'rowX_cell(10)',
  ],
  //second row of cells
  [
    'rowY_cell(01)',
    'rowY_cell(02)',
    'rowY_cell(03)',
    'rowY_cell(04)',
    'rowY_cell(05)',
    'rowY_cell(06)',
    'rowY_cell(07)',
    'rowY_cell(08)',
    'rowY_cell(09)',
    'rowY_cell(10)',
  ],
]

定義列名稱和順序:

我還可以說自從顯示 SQL 查詢以來從資料庫獲取的列的順序,這就是有序列表:

DATREA、HORREA、CODORI、NUMORP、CODPRO、CODDER、QTDRE1、QTDRFG、CODLOT、OPERADOR

我們在 js 中將其定義為字串數組,如下所示:

//ordered list of columns in the same order as the cols in data are supposed to be
const columnNames = ['DATREA','HORREA','CODORI','NUMORP','CODPRO','CODDER','QTDRE1','QTDRFG','CODLOT','OPERADOR'];

將行數組轉換為物件:

將行 data 轉換為物件數組,該數組具有以前面顯示的列列表命名的行列作為屬性:

function getRowObject(row){
  const rowObject = {};
  //for each col in columnNames
  columnNames.forEach((col, i)=>{
    //set the prop of rowObject named as col = the value at the i position in row
    rowObject[col] = row[i]; 
  });  
  return rowObject;
}

對於第一行資料(data[0])將傳回如下物件:

{
  "DATREA": "rowX_cell(01)",
  "HORREA": "rowX_cell(02)",
  "CODORI": "rowX_cell(03)",
  "NUMORP": "rowX_cell(04)",
  "CODPRO": "rowX_cell(05)",
  "CODDER": "rowX_cell(06)",
  "QTDRE1": "rowX_cell(07)",
  "QTDRFG": "rowX_cell(08)",
  "CODLOT": "rowX_cell(09)",
  "OPERADOR": "rowX_cell(10)"
}

如何在文件中顯示該資料?

根據具體目標,您有無限種方法。實際上,您一開始並不需要將數組轉換為對象,但它使得透過名稱而不是使用索引號來存取其列變得更容易。

無論如何,例如,如果您需要將每一行顯示為單一段落的內容,並將其所有列資料的串聯作為內容:

function appendRowsAsParagraphsInTarget(target, rowObjects){
  //you can loop through all the rows and print them on screen
  rowObjects.forEach( row => {
    //here we are converting the row object back to a list of values
    values = columnNames.map( columnName => row[columnName] );
    //here to a single string where values are separated by ', ' and wrapped in []
    values = values.map( value => `[${value}]`);
    values = values.join(', ');  
  
    //append the newly created p in target
    const p = document.createElement('p');
    p.textContent = values;
    target.append(p);
  });
}

演示:

這是到目前為止所說內容的現場演示:

//the array you are supposed to receive from your ajax call
const data = [
  //first row of cells
  [
    'rowX_cell(01)',
    'rowX_cell(02)',
    'rowX_cell(03)',
    'rowX_cell(04)',
    'rowX_cell(05)',
    'rowX_cell(06)',
    'rowX_cell(07)',
    'rowX_cell(08)',
    'rowX_cell(09)',
    'rowX_cell(10)',
  ],
  //second row of cells
  [
    'rowY_cell(01)',
    'rowY_cell(02)',
    'rowY_cell(03)',
    'rowY_cell(04)',
    'rowY_cell(05)',
    'rowY_cell(06)',
    'rowY_cell(07)',
    'rowY_cell(08)',
    'rowY_cell(09)',
    'rowY_cell(10)',
  ],
]

//ordered list of columns in the same order as the cols in data are supposed to be
const columnNames = ['DATREA','HORREA','CODORI','NUMORP','CODPRO','CODDER','QTDRE1','QTDRFG','CODLOT','OPERADOR'];

//transforming the original array of rows as array of objects where each one as col data as properties
const rowObjects = data.map( row => getRowObject(row) );

console.log(rowObjects);

//appending the rowObjects as p paragraph to #output_rows
const target = document.getElementById('output_rows');
appendRowsAsParagraphsInTarget(target, rowObjects);

function appendRowsAsParagraphsInTarget(target, rowObjects){
  //you can loop through all the rows and print them on screen
  rowObjects.forEach( row => {
    //here we are converting the row object back to a list of values
    values = columnNames.map( columnName => row[columnName] );
    //here to a single string where values are separated by ', ' and wrapped in []
    values = values.map( value => `[${value}]`);
    values = values.join(', ');  
  
    //append the newly created p in target
    const p = document.createElement('p');
    p.textContent = values;
    target.append(p);
  });
}

function getRowObject(row){
  const rowObject = {};
  //for each col in columnNames
  columnNames.forEach((col, i)=>{
    //set the prop of rowObject named as col = the value at the i position in row
    rowObject[col] = row[i]; 
  });  
  return rowObject;
}
.label{
  font-weight: bold;
}

#output_rows{
}

#output_rows > p{
  border: solid 1px lightgray;
  margin-bottom: 1em;
}

Showing all the table rows as p elements

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板