Update part of a page in jade?

*爱你&永不变心* 提交于 2019-12-06 15:02:40

问题


I'm trying to make a search and send back the result to the same site, I've got the search to work but I can't get the result to be sent back. I want the start site to render the information without page reload.

How can I send the search result back to the index.jade page without having to update it?

function pagelist(items, res) {
    var document='';
    var db = db_login;
    if ( items != null){
            items.forEach(function(item) {
            document += '<a href=share/'+item._id+' class="searchElement">'
            document += item.document 
            document += '</div>'
        })
        if(document != ''){
            res.send(document);
        }else{
        }
    }
}   

index.jade

extends layout
block content
    block child

child.jade

extends index
block child
    !{document}

回答1:


You can do it the following way:

First, you could update your index.jade like this:

extends layout
block content
    #content
        block child

And then, there should be some sort of function you call to get your results. I'll call it getResults. In the callback of that function you can now do the following:

getResults(function(results){
    document.getElementById("content").innerHTML = results;
});

I hope that helps.

UPDATE

I'll give you a complete example:

server.js

var express = require("express");

var i = 0;
function getResults(cb){
    cb("<div>Result "+(i++)+"</div><div>Result "+(i++)+"</div><div>Result "+(i++)+"</div>");
}

var app = express();
app.set("view engine","jade");
app.get("/",function(req,res){
    getResults(function(results){   
        res.render("page",{results:results});
    });
});
app.get("/results",function(req,res){
    getResults(function(results){       
        res.writeHead(200,"OK",{"Content-Type":"text/html"});
        res.end(results);
    });
});

app.listen(80);

views/page.jade

doctype html
html
    head
        script.
            function update(){
                var req = new XMLHttpRequest();
                req.open("GET","/results");
                req.onreadystatechange = function(){
                    if(req.readyState == 4){
                        document.getElementById("content").innerHTML = req.responseText;
                    }
                }
                req.send();
            }
    body
        #content!= results
        input(type="button",value="Update",onclick="update()")

Run it with node server.js and visit localhost. You should learn from it how it's done ;)



来源:https://stackoverflow.com/questions/26626249/update-part-of-a-page-in-jade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!