繁体   English   中英

res.render()函数呈现ejs页面不会刷新UI,但是会调用ejs页面

[英]res.render() function rendering an ejs page doesn't refresh the UI, but the ejs page get called

我有一个资源列表,需要根据位置进行过滤。 我有一个要过滤的表单,单击按钮后,将根据位置过滤数据。 我有一个AJAX请求,它向/ filterresources发送一个发布请求,并且还从数据库中获取与该条件匹配的数据,并且使用res.render()呈现resourcefilter.ejs,如下所示:

resourcefilter.js:

    router.post('/filterresources',function(req,res,next){
        var category = req.body.category;
        User.find({_id: {$ne: req.user._id}},(err,user) => {
            if(err) throw err;
            if(user)
            {
                db.findAll(Resource,{category:category})
                    .then(function(data){
                        res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
                    })
                    .catch(function(err){
                        next(err);
                    });
            }
            else {
                throw(err);
            }
        });


    });

The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.

resourcefilter.ejs:可以正确打印其中的所有控制台语句,但不会刷新UI。 任何帮助深表感谢。

<% layout('layout/layout') %>


<div class="container user-form py-5">
    <br>
    <%if(user.role == 'Administrator'){ console.log(user.role);%>
    <a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
    <%}%>
    </br>
    <span class="site-logo my-3">Our Resources</span>
    <div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
        <form id="filter-resources" class="mt-5">
            <div>
                <select class="custom-select" name="category" id="category">
                    <option selected>Select a location:</option>
                    <option value="Pittsburgh">Pittsburgh</option>
                    <option value="Allegheny County">Allegheny County</option>
                    <option value="Pennsylvania">Pennsylvania</option>
                    <option value="Outside Pennsylvania">Outside Pennsylvania</option>
                </select>
                <input class="filter" name="filter-resources" type="submit" value="Filter">
            </div>
        </form>
    </div>
    </form>

    <div class="container" style="margin-top: 2%;">

        <div class="row">
            <% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
            <div class="col-xs-12 col-sm-6 col-md-4">

                <div class="image-flip" ontouchstart="this.classList.toggle('hover');">

                    <div class="mainflip">

                        <div class="frontside">

                            <div class="card-custom">
                                <% console.log("Image"+resources[i].image);%>
                                <div class="card-body text-center">
                                    <img src="<%= resources[i].image %>" alt="" class="img-resources">
                                    <div class="card-title"><b><%= resources[i].name%></b></div>
                                    <div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
                                    <a href ="#"  class="card-title"></a>
                                    <a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
                                        Read More!</a>

                                    <br></br>         </div>
                            </div>
                            <br></br>
                        </div>



                    </div>

                </div>
            </div>


            <% } %>

        </div>
    </div>
</div>

调用/ filterresources的AJAX函数:

function filter_resources(e) {
    e.preventDefault();

    var category = $('#category :selected').text();
    console.log(category);
    const button = this.children[this.children.length - 1];

    //Form Handling with ajax

    $.ajax({

        url: '/filterresources',
        type: 'post',
        data: {category: category},
        dataType: 'json',

    });

    function refreshDiv() {     
        document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
    }

}

如果您的服务器没有任何错误,则可以使用前端解决方法:

$.ajax({

        url: '/filterresources',
        type: 'post',
        data: {category: category},
        dataType: 'json',

    }).then(() => location.reload());

请求完成后,将刷新您的页面。

您的ejs,js和html代码正确,问题是您的AJAX函数不会刷新页面的内容,而只会检索内容。 有2种解决方案:在EJS中,从“ render”更改为“ send”,然后在AJAX回调中对某些元素使用以innerHTML返回的值,或者进行表单提交,而不是jquery发布。 提交表单将导致页面重新加载。

location.reload()在这种情况下不起作用,因为过滤后的数据需要传递到页面上。 因此,我没有使用res.render(),而是按照建议使用了res.send。 请找到以下代码:

filterresources.js

router.post('/filterresources',function(req,res,next){
    var category = req.body.category;
    User.find({_id: {$ne: req.user._id}},(err,user) => {
        if(err) throw err;
        if(user)
        {
            var user = req.user._id;
            console.log(user);
            db.findAll(Resource,{category:category})
                .then(function(data){
                    res.send({msg: data, success: true,user: user });
                })
                .catch(function(err){
                    next(err);
                });
        }
        else {
            throw(err);
        }

    });
});

AJAX功能:

function filter_resources(e) {
    e.preventDefault();

    var category = $('#category :selected').text();
    console.log(category);
    const button = this.children[this.children.length - 1];

    //Form Handling with ajax

    $.ajax({
        url: '/filterresources',
        type: 'post',
        data: {category: category},
        dataType: 'json',
        success: function (response) {
            if (!response.success) {
                window.alert(response.msg);
            }
            if (response.success) {
                var resource = response.msg;
                var userInfo = response.user;
                $('#resfilter').html(""); // reset the contents in the div
                var html = `<div class="row">`;
                for(var i=0;i<resource.length;i++) {
                    html += `<div class="col-xs-12 col-sm-6 col-md-4">
                                <div class="image-flip" ontouchstart="this.classList.toggle('hover');">
                                <div class="mainflip"> <div class="frontside"> <div class="card-custom">
                                <div class="card-body text-center">`;
                    html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
                    html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
                    html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
                    html += `<a href ="#"  class="card-title"></a>`;
                    html += `<a href = ${resource[i].website} id="singlebutton" name="singlebutton" class="btn btn-primary">Read More!</a>`;
                    html += `<br>`;
                    html += `</br></div></div><br></br></div></div></div></div>`;
                }
                    html += `</div></div></div></div>`;
                    }
                    document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
                }
                })
}

暂无
暂无

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

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