Anonymous
HTML JavaScript, титул рендеринга на основе метода SQL запроса
Сообщение
Anonymous » 01 июн 2025, 17:43
В настоящее время я делаю шаблон для своих школьных вещей. - Я отправляю проект, поэтому, если у вас есть какие -либо другие предложения вне моего первоначального запроса, я рад их получить -. < /P>
Заранее спасибо.
Код: Выделить всё
const express = require('express');
const mysql = require('mysql');
const app = express();
app.use(express.static("public"));
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: ''
});
app.get('/api/table1', (req, res) => {
db.query('SELECT * FROM table1', (err, results) => {
if (err) return res.status(500).json({ error: err });
res.json(results);
});
});
app.get('/api/table2', (req, res) => {
db.query('SELECT * FROM table2', (err, results) => {
if (err) return res.status(500).json({ error: err });
res.json(results);
});
});
app.get('/api/select-options', (req, res) => {
db.query('SELECT selectoption FROM table1', (err, results) => {
if (err) return res.status(500).json({ error: err });
res.json(results);
});
});
app.get('/api/filter', (req, res) => {
const value = req.query.value;
db.query('SELECT * FROM table1 t1 JOIN table2 t2 ON t1.attribute = t2.attribute WHERE t2.attribute = ?', [value], (err, results) => {
if (err) return res.status(500).json({ error: err });
res.json(results);
});
});
app.get('/api/title-info', (req, res) => {
const id = req.query.id;
db.query('SELECT * FROM table1 WHERE x = ?', [id], (err, results) => {
if (err) return res.status(500).json({ error: err });
if (results.length === 0) return res.json({ info: 'No data' });
const info = results[0].RESULTFIELD;
res.json({ info });
});
});
app.listen(3000, () => console.log('Server running on port 3000'));
< /code>
frontend: (index.html и index.js): < /p>
function showSection(id)
{
['section1', 'section2', 'section3'].forEach(sid =>
{
document.getElementById(sid).style.display = 'none';
});
document.getElementById(id).style.display = 'block';
}
function loadTable1()
{
fetch('/api/table1')
.then(res => res.json())
.then(data =>
{
const container = document.getElementById('table1');
container.innerHTML = '';
if (!data.length) return;
const table = document.createElement('table');
const headers = Object.keys(data[0]);
const headerRow = document.createElement('tr');
headers.forEach(h =>
{
const th = document.createElement('th');
th.textContent = h;
headerRow.appendChild(th);
th.addEventListener('click', () =>
{
const sortedData = data.sort((a, b) =>
{
if (a[h] < b[h]) return -1;
if (a[h] > b[h]) return 1;
return 0;
});
renderTable('table1', sortedData);
});
});
table.appendChild(headerRow);
data.forEach(row =>
{
const tr = document.createElement('tr');
headers.forEach(h =>
{
const td = document.createElement('td');
td.textContent = row[h];
tr.appendChild(td);
});
table.appendChild(tr);
});
container.appendChild(table);
});
}
function loadTable2()
{
fetch('/api/table2')
.then(res => res.json())
.then(data =>
{
const container = document.getElementById('table2');
container.innerHTML = '';
if (!data.length) return;
const table = document.createElement('table');
const headers = Object.keys(data[0]);
const headerRow = document.createElement('tr');
headers.forEach(h =>
{
const th = document.createElement('th');
th.textContent = h;
headerRow.appendChild(th);
});
table.appendChild(headerRow);
data.forEach(row =>
{
const tr = document.createElement('tr');
headers.forEach(h =>
{
const td = document.createElement('td');
td.textContent = row[h];
tr.appendChild(td);
});
tr.addEventListener('mouseover', () =>
{
fetch(`/api/title-info?id=${ row.id }`)
.then(res => res.json())
.then(info =>
{
tr.title = info.info || 'No data';
})
.catch(() =>
{
tr.title = 'Error occured';
});
});
table.appendChild(tr);
});
container.appendChild(table);
});
}
async function loadDropdown()
{
const dropdown = document.getElementById('dropdown');
dropdown.innerHTML = 'Kérem válasszon!';
try
{
const res = await fetch('/api/select-options');
const data = await res.json();
data.forEach(row =>
{
const key = Object.values(row)[0];
dropdown.innerHTML += `${ key }`;
});
loadFiltered();
} catch (err)
{
console.error('Failed to load dropdown options:', err);
}
}
async function loadFiltered()
{
const value = document.getElementById('dropdown').value;
if (value !== '')
{
try
{
const res = await fetch(`/api/filter?value=${ (value) }`);
const data = await res.json();
renderTable('filtered', data);
} catch (err)
{
console.error('Failed to load filtered data:', err);
}
} else
{
document.getElementById('filtered').innerHTML = '';
}
}
function renderTable(id, data)
{
const container = document.getElementById(id);
container.innerHTML = '';
if (!data.length) return;
const table = document.createElement('table');
const headers = Object.keys(data[0]);
const headerRow = document.createElement('tr');
headers.forEach(h =>
{
const th = document.createElement('th');
th.textContent = h;
headerRow.appendChild(th);
th.addEventListener('click', () =>
{
const sortedData = data.sort((a, b) =>
{
if (a[h] < b[h]) return -1;
if (a[h] > b[h]) return 1;
return 0;
});
renderTable('table1', sortedData);
});
});
table.appendChild(headerRow);
data.forEach(row =>
{
const tr = document.createElement('tr');
headers.forEach(h =>
{
const td = document.createElement('td');
td.textContent = row[h];
tr.appendChild(td);
});
table.appendChild(tr);
});
container.appendChild(table);
}
loadTable1();
loadTable2();
loadDropdown();
showSection('section1');
API Page
Section 1
Section 2
Section 3
table1
table2
selector
< /code>
А вот та часть, в основном мне нужна помощь с: < /p>
tr.addEventListener('mouseover', () =>
{
fetch(`/api/title-info?id=${ row.id }`)
.then(res => res.json())
.then(info =>
{
tr.title = info.info || 'No data';
})
.catch(() =>
{
tr.title = 'Error occured';
});
});
Можно ли предварительно распространять названия для каждой строки соответственно?
Подробнее здесь:
https://stackoverflow.com/questions/796 ... ery-method
1748789029
Anonymous
В настоящее время я делаю шаблон для своих школьных вещей. - Я отправляю проект, поэтому, если у вас есть какие -либо другие предложения вне моего первоначального запроса, я рад их получить -. < /P> Заранее спасибо.[code]const express = require('express'); const mysql = require('mysql'); const app = express(); app.use(express.static("public")); const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: '' }); app.get('/api/table1', (req, res) => { db.query('SELECT * FROM table1', (err, results) => { if (err) return res.status(500).json({ error: err }); res.json(results); }); }); app.get('/api/table2', (req, res) => { db.query('SELECT * FROM table2', (err, results) => { if (err) return res.status(500).json({ error: err }); res.json(results); }); }); app.get('/api/select-options', (req, res) => { db.query('SELECT selectoption FROM table1', (err, results) => { if (err) return res.status(500).json({ error: err }); res.json(results); }); }); app.get('/api/filter', (req, res) => { const value = req.query.value; db.query('SELECT * FROM table1 t1 JOIN table2 t2 ON t1.attribute = t2.attribute WHERE t2.attribute = ?', [value], (err, results) => { if (err) return res.status(500).json({ error: err }); res.json(results); }); }); app.get('/api/title-info', (req, res) => { const id = req.query.id; db.query('SELECT * FROM table1 WHERE x = ?', [id], (err, results) => { if (err) return res.status(500).json({ error: err }); if (results.length === 0) return res.json({ info: 'No data' }); const info = results[0].RESULTFIELD; res.json({ info }); }); }); app.listen(3000, () => console.log('Server running on port 3000')); < /code> frontend: (index.html и index.js): < /p> function showSection(id) { ['section1', 'section2', 'section3'].forEach(sid => { document.getElementById(sid).style.display = 'none'; }); document.getElementById(id).style.display = 'block'; } function loadTable1() { fetch('/api/table1') .then(res => res.json()) .then(data => { const container = document.getElementById('table1'); container.innerHTML = ''; if (!data.length) return; const table = document.createElement('table'); const headers = Object.keys(data[0]); const headerRow = document.createElement('tr'); headers.forEach(h => { const th = document.createElement('th'); th.textContent = h; headerRow.appendChild(th); th.addEventListener('click', () => { const sortedData = data.sort((a, b) => { if (a[h] < b[h]) return -1; if (a[h] > b[h]) return 1; return 0; }); renderTable('table1', sortedData); }); }); table.appendChild(headerRow); data.forEach(row => { const tr = document.createElement('tr'); headers.forEach(h => { const td = document.createElement('td'); td.textContent = row[h]; tr.appendChild(td); }); table.appendChild(tr); }); container.appendChild(table); }); } function loadTable2() { fetch('/api/table2') .then(res => res.json()) .then(data => { const container = document.getElementById('table2'); container.innerHTML = ''; if (!data.length) return; const table = document.createElement('table'); const headers = Object.keys(data[0]); const headerRow = document.createElement('tr'); headers.forEach(h => { const th = document.createElement('th'); th.textContent = h; headerRow.appendChild(th); }); table.appendChild(headerRow); data.forEach(row => { const tr = document.createElement('tr'); headers.forEach(h => { const td = document.createElement('td'); td.textContent = row[h]; tr.appendChild(td); }); tr.addEventListener('mouseover', () => { fetch(`/api/title-info?id=${ row.id }`) .then(res => res.json()) .then(info => { tr.title = info.info || 'No data'; }) .catch(() => { tr.title = 'Error occured'; }); }); table.appendChild(tr); }); container.appendChild(table); }); } async function loadDropdown() { const dropdown = document.getElementById('dropdown'); dropdown.innerHTML = 'Kérem válasszon!'; try { const res = await fetch('/api/select-options'); const data = await res.json(); data.forEach(row => { const key = Object.values(row)[0]; dropdown.innerHTML += `${ key }`; }); loadFiltered(); } catch (err) { console.error('Failed to load dropdown options:', err); } } async function loadFiltered() { const value = document.getElementById('dropdown').value; if (value !== '') { try { const res = await fetch(`/api/filter?value=${ (value) }`); const data = await res.json(); renderTable('filtered', data); } catch (err) { console.error('Failed to load filtered data:', err); } } else { document.getElementById('filtered').innerHTML = ''; } } function renderTable(id, data) { const container = document.getElementById(id); container.innerHTML = ''; if (!data.length) return; const table = document.createElement('table'); const headers = Object.keys(data[0]); const headerRow = document.createElement('tr'); headers.forEach(h => { const th = document.createElement('th'); th.textContent = h; headerRow.appendChild(th); th.addEventListener('click', () => { const sortedData = data.sort((a, b) => { if (a[h] < b[h]) return -1; if (a[h] > b[h]) return 1; return 0; }); renderTable('table1', sortedData); }); }); table.appendChild(headerRow); data.forEach(row => { const tr = document.createElement('tr'); headers.forEach(h => { const td = document.createElement('td'); td.textContent = row[h]; tr.appendChild(td); }); table.appendChild(tr); }); container.appendChild(table); } loadTable1(); loadTable2(); loadDropdown(); showSection('section1'); API Page Section 1 Section 2 Section 3 table1 table2 selector < /code> А вот та часть, в основном мне нужна помощь с: < /p> tr.addEventListener('mouseover', () => { fetch(`/api/title-info?id=${ row.id }`) .then(res => res.json()) .then(info => { tr.title = info.info || 'No data'; }) .catch(() => { tr.title = 'Error occured'; }); }); [/code] Можно ли предварительно распространять названия для каждой строки соответственно? Подробнее здесь: [url]https://stackoverflow.com/questions/79647641/html-javascript-render-title-based-on-sql-query-method[/url]