我想将我的products数组传递给html页面。
app.get("/", function(req, res){
res.render(__dirname+ "/product.html",{data: Product_Array_fromDatabase});
})
在HTML页面的客户端,我试图查看/将循环它
<script type="text/javascript">
var data = JSON.stringify(data);
alert(data) // Says Undefined
</script>
我没有获得数据的价值?有什么帮助吗?
答案 0 :(得分:1)
我做了ejs渲染数据并使用jquery ajax将数据发送到页面并提醒它可能对你有用
<强> hello.js 强>
var express = require('express');
var app = express();
var engine = require('ejs-locals');
app.engine('ejs', engine);
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.get('/', function(req, res){
res.render('index',{user:"John Smith"})
});
app.get('/helo', function(req, res){
res.send({'data':'hello'});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
<强> index.ejs 强> 在名为views --- path appname / views / index.ejs
的目录中<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("/helo", function(data, status){
console.log(data);
var result = data
alert(result['data'])
});
});
});
</script>
</head>
<body>
welcome <%= user%><br>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>