How to render data through DOM instead of through table
P粉207483087
P粉207483087 2024-04-04 18:17:27
0
1
3786

I have a question about an application I'm creating, I'm using an Oracle database, and I'm getting information from the database and presenting it on the screen via a table, but I want to try processing the data individually, like creating a paragraph and display a value.

I can only present data through tables, are there any other ways? If anyone can help me, thank you very much.

I accept all tips to improve the code.

MyIndex.htmlPage

<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>

This is my Index.js where I make a selection and send the data

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

reply all(1)
P粉706038741

Assumption:

Since I cannot reproduce the scenario exactly, I will focus on the client side and just take it for granted that your backend endpoint will correctly return an array, for example: data[iRow][iColumn]

This assumption comes from the line cell1.innerHTML = data[i][0];

Static defined data example:

I'm not quite sure if the data is just an array of arrays, or if there is some way to address the column values ​​by column name. Anyway, we'll stick with the plain array paradigm here since it seems to work according to your own words.

Here we define a data array, containing 2 rows, each row has 10 columns:

//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)',
  ],
]

Define column names and order:

I can also say the order of the columns fetched from the database since the SQL query was shown, this is the ordered list:

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

We define it as a string array in js, as shown below:

//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'];

Convert row array to object:

Convert the row data to an array of objects that has as properties rows and columns named after the column list shown earlier:

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;
}

For the first row of data (data[0]) the following object will be returned:

{
  "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)"
}

How to display this data in the document?

Depending on the specific goal, you have unlimited ways to do it. You don't actually need to convert the array to an object in the first place, but it makes it easier to access its columns by name rather than using index numbers.

Anyway, if for example you need to display each row as the content of a single paragraph, with the concatenation of all its column data as content:

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);
  });
}

Demo:

Here is a live demonstration of what has been said so far:

//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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template