Answer the question
In order to leave comments, you need to log in
How to optimize multiple post queries to the database on one page?
When the button is clicked, a POST request is sent to the server and the list is loaded. The rasdel variable is generated based on the id of the button that the user clicked on (the first time I write such a script,
then I take the id - is that correct? then I process it on the server)
var rasdel = ''; // разделы
function chart_ajax_add(rasdel ){
$.ajax({ //на раздела выдаем список
type: "POST",
url: "/mar",
data: rasdel ,
contentType: "text/plain",
success:function (text) {
for(i = 0; i < text.length; i++){
$('.razdel').find('ul').append('<li attr="'+ (i+1) + '">' + (i+1) + '. ' + text[i]['name'] +'</li>');
}}
}).fail(function () {
console.log('fail');
});
};
app.post('/mar', (req, res) => {
var requ = JSON.parse(req.body);
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: requ.rasdel
});
let sql = 'SELECT * FROM subcharter WHERE `rasdel _id` =' + requ.rasdel ;
db.query(sql, (err, result) =>{
if (err) throw err;
let mas = JSON.stringify(result);
// console.log(mas);
res.type('application/json');
res.send(mas);
});
db.end();
});
Answer the question
In order to leave comments, you need to log in
1. No need to create a connection to the database every time. You need to do this once when starting the application. Or a connection pool.
2. It is not necessary to make requests to the database like this - it is necessary through prepared requests.
3. As part of a connection to one server, you can make requests to different databases, you only need to explicitly specify them in the request
4. Requests can be cached
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question