2017-03-17 16 views
0

我正在使用node.js和google map api開發web應用程序。 我想從MySQL DB發送數據到客戶端並使用它們的座標繪製標記。讓我說明我寫的是什麼。如何在Node.js中將MySQL數據發送到html(google map api embedded)

app.js(服務器端):

app.get('/result/:l_area', function(request, response){ 
fs.readFile('result.html', 'utf8', function(error, data) { 
    client.query('SELECT * FROM Locations WHERE l_area=?', [request.params.l_area], function(error, result){ 
     response.writeHead(200, {'Context-Type': 'text/html'}); 
     response.end(data, {data: result}); 
    }); 
});}); 

正如你可以看到,路由有它的PARAM,它決定什麼樣的數據提取。當我使用ejs製作類似的路由頁面時,它是成功的。但是......

result.html:

function initMap(){ 
     map = new google.maps.Map(document.getElementById('map'), { 
      zoom: 8, 
      center: new google.maps.LatLng(xxx,xxx) 
     }); 

     $.each(data, function(key, item){ 
      var latLng = new google.maps.LatLng(item.latitude, item.longitude); 
      var marker = new google.maps.Marker({ 
       position: latLng, 
       map: map, 
       title: item.l_name 
      }); 
     }); 

我得到了什麼只是一個錯誤消息「未捕獲的ReferenceError:數據沒有定義」從Chrome瀏覽器開發工具。如何將數據發送到HTML頁面以繪製標記?謝謝。

回答

0

您需要從前端獲取獲取請求。既然你使用JQuery,你可以做你的前端下面的JavaScript

$.get("/result", function(data) { 
    $.each(data, function(key, item){ 
      var latLng = new google.maps.LatLng(item.latitude, item.longitude); 
      var marker = new google.maps.Marker({ 
       position: latLng, 
       map: map, 
       title: item.l_name 
      }); 
     }); 
}); 
+0

對不起,我遲到了。你給我的方法不適合我的工作,但提醒我一些必要的。也許我必須使用socket.io才能在一個URL中的服務器和客戶端之間傳輸數據。再見。 –

相關問題