简体   繁体   中英

node.js ejs rerender div afte ajax

My issue is update div block after succes ajax call. so I do it like that:

My div:

<div class="lists">
                <% for(var i=0; i<searchItem.length; i++) {%>
                <a class="list-link" href="#"><div class="list"><%= searchItem[i] %></div></a>
                <% } %>
            </div>

My jquery ajax call:

 $.ajax({
                    url: '/search?val=' + encodeURIComponent($('#search-input').val()),
                    success: function(data) {
                        console.log('DATA-' + data);
                        new EJS({url:' /views/dropdown.ejs'}).update('lists',data)
                    }
                });

My project structure:

在此处输入图片说明

But I got 404 error, because ejs cannot see dropdown.ejs template( http://localhost:3000/views/dropdown.ejs NOT FOUND). Why?

Another question what type of selector I need write in .update('lists',data) , Id or class of my div block?

I am assuming that you are using Express and views/dropdown.ejs is a view in your express backend.

If my assumption is correct, you can not directly access view of your backend. You have to create a router for this view or you can put this template in your static folder.

router.get('/template/:templateName', function(req, res){
    res.render(req.params.templateName, { title: 'Template' });
});

// Or put your template inside public folder

app.use(express.static(path.join(__dirname, 'public')));

As for your second question regarding the selector for your DOM.It depends on what you want to achieve. Using class selector will get all the DOM with that class name and if give you an array of DOM, as for the ID (needs to be unique on a certain page) it will select the single DOM.

Looking at your sample, I think you need to use ID and target that DOM for updating the content.

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