简体   繁体   中英

res.render() into a div with express

I am using nodejs with express and I'm trying to load an ejs into a div like this:

app.js (server side)

//SHOW
app.get("/courses/:id", function(req,res){
    console.log("requested");
    res.render('courses/show', function(err, html){
        if(err){
            console.log(err);
        }
        else{
            console.log(html);
        }
    });
});

this prints in the console the HTML that is supposed to be loaded into the DIV

main.js (client side)

$(".course_link").on('click', function(){
  $.ajax({ 
      url: '/courses/asd',
      type: 'get',
      success: function(view) {
         $('#show_load').html(view);
      }
  });
});

I also tried:

$(".course_link").on('click', function(){
      $('#show_load').load('/courses/asd', function(){
        alert('ayy');
      });
});

this alerts 'ayy', but won't load the file

HTML (ejs)

<div class="col-sm-8 courses-menu" id="show_load">

</div>

But it won't load the HTML into the DIV, but it does console.logs 'requested' when I click the first time, it should make a request with each click too..

I think you need to send() the html:

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('courses/show', function(err, html) {
  res.send(html);
});

https://expressjs.com/en/4x/api.html#res.get

Also make sure your PATH is complete:

var PATH = 'http://localhost:3000';    
$(".course_link").on('click', function(){
          $('#show_load').load(PATH + '/courses/asd', function(){
            alert('ayy');
          });
    });

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