[英]How do you read data from mySQL using node.js and post back to HTML?
我正在嘗試從MySQL
讀取數據,然后如果名稱匹配,則將數據發回到同一頁上。 我似乎沒有將結果返回頁面? 怎么了?
我正在學習使用NodeJS
,它可以在控制台上運行,但是嘗試在HTML上運行
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "petra",
password: "password",
database: "mydatabase"
});
function readmySQL() { // function readmySQL is triggered from a html page on click
var getname = document.getElementById("fullname").value;
con.connect(function(err) {
if (err) throw err;
//Select all customers and return the result object:
con.query("SELECT name, address, contact FROM myaddress", function (err, result, fields) {
if (err) throw err;
//console.log(result);
Object.keys(result).forEach(function(key) {
var row = result[key];
if (getname == row.name){ // match entered name to datatbase user name
document.getElementById("display_result").innerHTML = "Hello you have entered " + getname;
}
console.log(row.name + " , " + row.address + " , " + row.contact);
});
connection.end();
});
});
}
NodeJS在服務器上運行。 HTML文件中的腳本在客戶端上運行。 您不在客戶端上包含服務器代碼。 而是從客戶端將消息發送到服務器代碼,並解釋結果。 因此,執行此操作的標准方法是在服務器上定義一個資源,該資源將生成要生成的內容或數據,並僅使用常規頁面加載或“ ajax”從客戶端檢索該內容或數據。
因此,您必須通過節點js創建一個http服務器(檢查express js),以在服務器中實現您的Web服務,並通過ajax從前端調用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.