简体   繁体   中英

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

I want to pass my products array to html page.

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

<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

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

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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