Sye*_*mil 2 html javascript ejs node.js
我有以下快递应用程序,它只是呈现sample.ejs页面.在该页面上,当我按下按钮时,附加的脚本将div文本更改为"这是来自J QUERY.我希望同样的事情发生但我希望数据来自数据库.在我的快递应用程序中,如果我尝试使用res.render();每次我点击按钮然后重新加载我不想要的页面.那么有没有办法实现这一点而不重新加载页面只更新页面的一部分?我搜索了堆栈溢出和网络,但无法得到一个合适的答案,或者我可能无法理解.我知道这是一个非常基本的问题.
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} );
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
现在这就是我想要做的
<!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>
Run Code Online (Sandbox Code Playgroud)
注意:我不是问如何查询数据库
-谢谢
您必须在后端定义并返回要返回要显示的信息的端点:
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} );
});
app.get('/api/books', function(req, res) {
res.json({
message: 'Your database information'
});
});
Run Code Online (Sandbox Code Playgroud)
然后在你的前端你需要调用api端点,如:
sample.ejs
<script>
$(document).ready(function () {
var my_div = $("#holder");
$("#HButton").on("click", function () {
$.ajax({
url: "/api/books"
})
.done(function( data ) {
console.log( "Sample of data:", data );
$('#holder').html(data.message);
});
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到有关使用jquery进行ajax调用的更多信息.
但是我建议你使用任何框架,如angular或react,以便更容易在html中呈现数据,否则你将不得不使用jquery编写大量代码.