2

好的,所以我有代码可以将我带到我的索引页面,然后我通过 ajax 调用代码以从我的 mongoose db 中返回结果。所有这些调用都在工作,但我似乎无法弄清楚如何让我的代码在 ajax 调用成功后执行以在当前页面的一部分中加载另一个较小的 ejs 文件?我读过一些东西说我需要渲染 ejs 服务器端,但是如何调用服务器并让它只更新页面的一部分而不是整个页面加载。我正在尝试在已经产生完整结果的页面上执行搜索功能,因此我想用已搜索的内容替换完整结果。这是我对数据库的导出调用:

exports.index = function(req, res, next){
    Recipe.find().
        sort('-updated_at').
        exec(function(err, recipes, count){
            if( err ) return next( err );
            res.render('index', { title: 'Recipe Finder Index', recipes:recipes });
        })

    };

    exports.search = function(req, res, next){
    var param=req.params.search;
    console.log(param);
    Recipe.find({"fn":new RegExp(param)}).
        sort('-updated_at').
        exec(function(err, recipes, count){
            if( err ) return next( err );
            //res.render('index', { title: 'Recipe Finder Index', recipes:recipes });
            res.contentType('json');
            console.log(JSON.stringify({recipes:recipes}));
            res.write(JSON.stringify({recipes:recipes}));
            res.end();
        })
    };

那么我在脚本标签中加载的第一个 ejs 文件中有这个:

$('#submitSearch').click(function(){ 
        console.log("clicked");
        $.ajax({ 
            url: '/ajax/'+$('input[name=search]').val()
            , type: 'POST'
            , cache: false
            , complete: function() {
            //called when complete
            console.log('process complete');
        },
        success: function(data) {
            console.log(data);
            console.log('process sucess');
            //returns correct data, but then how can I call ejs?         
        },
    });

因此,代码为我提供了我正在寻找的对象,它从数据库中获取数据,但我无法找到代码,让我的网站的一部分重新加载一个 ejs 文件,其中包含我得到的新对象。我在网上看到不再支持部分内容,我应该使用包含,但看起来它只为网站的一部分提供了 ejs,并没有告诉我如何使用来自 ajax 的新数据呈现 ejs?

4

0 回答 0