我正在嘗試構建一個實時網頁以顯示一些實時統計信息。這個網頁有12個組件。我在SetTimeout中使用Ajax來更新每個組件。由於我想以不同頻率更新每個組件,因此我爲每個組件編寫了一個setTimeout函數,併爲每個組件提供了一個鏈接(在「main.js」中定義)。看起來像:在Node.js中,如何更新不同頻率頁面的不同組件?
(function poll() {
setTimeout(function() {
$.ajax({
url: url1,
type: 'GET',
success : function(info){
var object = document.getElementById("1");
object.textContent = info;
}, complete: poll });
}, 5000);
})();
...
...
(function poll() {
setTimeout(function() {
$.ajax({
url: url12,
type: 'GET',
success : function(info){
var object = document.getElementById("12");
object.textContent = info;
}, complete: poll });
}, 10000);
})();
而在我的「server.js」,我希望連接到數據庫只有一次,然後渲染不同的組件。數據庫的配置將依賴的鏈接,所以我安排這樣的應用:
app.get('/:A/:B', function(req,res){
var A= req.params.A;
var B = req.params.B;
var config = something relies on A and B
var client = new pg.Client(config);
client.connect(function(err){
if (err) {
console.log("Error occurred when try to connect the database",err);
}
else {
res.sendFile(__dirname + '/public/main.html');
app.get('/main.js', function(req,res){
res.sendFile(__dirname + '/public/main.js');
});
app.get('/url1',function(req,res) {
//query database and send the data url1 needs
});
...
...
app.get('/url12',function(req,res) {
//query database and send the data url12 needs
});
})
我要問,如果寫「app.get()」中的「app.get()」之類上面的代碼是很好的做法。如果不是,我如何保持與數據庫的全局連接並將其用於不同的組件?另外,我可以對這個網絡應用程序有任何改進嗎?我很新Node.js
使用websocket代替AJAX獲得更多性能 –
您不能將'app.get()'放在另一個'app.get()'內。這些處理程序安裝在您的服務器上供所有用戶使用,因此這絕不會是所需的行爲。 – jfriend00