我有以下快速應用程序,它只呈現sample.ejs頁面。當我按下按鈕時,附加的腳本將div文本更改爲 「這是J QUERY。使用res.render();每次我點擊按鈕,然後重新加載我不想要的頁面,那麼有沒有一種方法可以實現這一點,而無需重新加載頁面,只更新頁面的一部分? 我已經搜索堆棧溢出和Web,但不能得到一個合適的答案也許我只是感到無法理解。我知道這是要問一個很基本的東西。使用NODE.JS和EJS更新HTML頁面的一部分
APP.js
var express = require('express');
var app = express();
app.use(express.static('public'));
app.use(express.static('./src/views'));
app.set('views', './src/views');
app.set('view engine' , 'ejs');
app.listen(3000 , (err)=>{console.log('Listening')});
app.get('/' , function(req , res) {
res.render('sample' , {result_from_database: res.body});
});
個
sample.ejs
<!doctype html>
<html lang="en">
<head>
<title>Sample HTML File</title>
</head>
<body>
<div id="holder">
WELCOME
</div>
<form>
<button type="button" id="HButton"> HELLO </button>
</form>
</body>
<script>
$(document).ready(function() {
var form = $("#holder");
$("#HButton").on("click", function() {
form.html("THIS IS FROM J QUERY");
});
});
</script>
<script src="/lib/jquery/dist/jquery.js"></script>
</html>
現在,這就是我想要做的
<!doctype html>
<html lang="en">
<head>
<title>Sample HTML File</title>
</head>
<body>
<div id="holder">
<%= result_from_database %>
</div>
<form>
<button type="button" id="HButton"> HELLO </button>
</form>
</body>
<script>
$(document).ready(function() {
var my_div = $("#holder");
$("#HButton").on("click", function() {
/* Tell app.js that I clicked a button and then app.js
query the database and using ejs or something else update the
my_div inner html with the database result without
reloading page */
});
});
</script>
<script src="/lib/jquery/dist/jquery.js"></script>
</html>
注:我不問如何查詢數據庫
-Thanks
你在問什麼需要客戶端JavaScript,通常稱爲Ajax。如果你搜索這個名字,有很多教程。 – Quentin
你必須在node.js中定義一個api端點,以json格式檢索所需的信息。然後從前端開始,您可以使用JQuery,Angular或React調用api並在前端顯示信息。 –