简体   繁体   English

Express.js发送数据以查看未发送,出了什么问题

[英]Express.js send data to view not sent, What went wrong

I want to pass my products array to html page. 我想将我的产品数组传递到html页面。

app.get("/", function(req, res){
    res.render(__dirname+ "/product.html",{data: Product_Array_fromDatabase});
})

At client side in HTML page am trying to view / will loop it 在HTML页面的客户端,我试图查看/将其循环

<script type="text/javascript">
    var data = JSON.stringify(data);
   alert(data) // Says Undefined
</script>

I am not getting value of data? 我没有得到数据的价值? Any help? 有什么帮助吗?

js i made the ejs to render the data and used jquery ajax to send the data to the page and alert it may be this will useful to you js我制作了ejs来呈现数据,并使用jquery ajax将数据发送到页面并警告它可能对您有用

hello.js 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 in the directory called views---path appname/views/index.ejs 目录中的index.ejs称为views ---路径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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM