suchen

Heim  >  Fragen und Antworten  >  Hauptteil

So rendern Sie Daten über DOM statt über eine Tabelle

Ich habe eine Frage zu einer Anwendung, die ich erstelle. Ich verwende eine Oracle-Datenbank und erhalte Informationen aus der Datenbank und präsentiere sie auf dem Bildschirm in Form einer Tabelle. Ich möchte jedoch versuchen, die Daten einzeln zu verarbeiten Erstellen eines Absatzes und Anzeigen eines Werts.

Ich kann Daten nur über Tabellen darstellen, gibt es eine andere Möglichkeit? Wenn mir jemand helfen kann, vielen Dank.

Ich akzeptiere alle Tipps zur Verbesserung des Codes.

Meine Index.htmlSeite

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

Dies ist mein Index.js, in dem ich Auswahlen treffe und Daten sende

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粉207483087P粉207483087259 Tage vor3774

Antworte allen(1)Ich werde antworten

  • P粉706038741

    P粉7060387412024-04-05 14:02:39

    假设:

    由于无法准确重现该场景,我将重点关注客户端,只理所当然地认为您的后端端点将正确返回一个数组,例如: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

    Antwort
    0
  • StornierenAntwort