Implement the screen rendered by ejs template asynchronously with ajax

Asked 2 years ago, Updated 2 years ago, 88 views

Developing node.js + express.

You want to implement the comment writing function asynchronously. (To prevent reloading)

ejs and templates.

Go to the bulletin board post+comment page

router.get('/topic', function(req, res) {
    models.Board.findAll({
    })
    .then(function(data){
      res.render('topic',data); // topic.ejs page
    });
});

I rendered topic.ejs like this.

Topic.ejs implements comment writing with ajax.

The comments here...


<% if(user) { %>
<p>Nickname</p>
<% } else if { %>
<p>Non-login</p>
<% } %>
<p>Content of Comments<p>

It's in form.

If you succeed in writing this comment

$('#comment').append(
`<% if(user) { %>
<p>Nickname</p>
<% } else if { %>
<p>Non-login</p>
<% } %>
<p>content<p>

);


You are about to process it as an expression.

ejs is the role of rendering, and I know that this rendered code should be implemented in ajax, so please help me with this conditional part.

ejs ajax node.js

2022-09-21 21:01

1 Answers

I think there are two ways

The key point is that the contents of the comments remain unchanged, and if you are a user, you will only print out your nickname or non-login.

So even if you append in that format, those ejs won't work because they're already rendered on the server.

If you re-render it, it will come out, but the screen might blink or something

<% if(user) { %>
<p>Nickname</p>
<% } else if { %>
<p>Non-login</p>
<% } %>
<p>Content of Comments<p>

Check whether the server is a user or not and print it out as html

// node.js Router
...
    If(user) { // If you're a user, you just need to send your nickname
        res.send('<p>'+Nickname variable+'</p><p>Comments</p>');
    } else { // if you're not a user 
        res.send('<p>non-login</p><p> Comments</p>');
    }
...

Then, you can add it as it is

$('#comment').append(data); // ajax Put the imported data as it is if successful

If the Ajax request is successful, the server sends a login user or a non-login user in JSON form and does it on the client.

// Login user
res.send ({logged: True, nickname: "Nickname"});
// Non-login user's noodles
res.send({logined: False});

After sending it this way, the client

data = JSON.parse(data); // Parse the imported data

if (data.logined == True) {
    // If you are a login user,
    $("#comment").append("<p>"+data.nickname+"</p><p>Comments</p>");
} } else {
    // if not
    $("#comment").append("<p>non-login</p><p>Comments</p>"));

}

It's possible in this way.

I solved it hard, but to put it simply, let's distinguish whether it's a server or a client or not.


2022-09-21 21:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.