简体   繁体   中英

i tried to upate my ejs page with fetch but it doesn't work

i tried to build a simple app but i got a problem my app is just some peoples data saved in the db and the target is just to display them on the screen but we can search those people by name. i have a ejs page and javascript file connected to him

js code:

document.querySelector(".search__box_input").addEventListener("click", async function(event) {
    fetch("/", {
        method: "get",
        headers: new Headers({'search': searchButton.value})
    })
})

node code:

app.get("/", async(req, res) => {
    if(!req.headers["search"] || req.headers["search"] === ''.trim()) {
        return res.render("home", persons: await personSchema.find({}).limit(10)}) // personSchema is my mongoose schema
    } else {
        const foundDocuments = await personSchema.find({"name.first": req.headers["search"]})
        console.log(foundDocuments); // i got my document correctly
        if(!foundDocuments) return res.send("could'nt find the user")
        return res.render("home", {
            persons: foundDocuments // It doesn't render again
        })
    }
})

i want to render the ejs again.. someone can help me pls?

The point of Ajax is that you make a request with JavaScript and the response is given back to your JavaScript to process. Typically this would involve doing a DOM update .

Your JavaScript is completely ignoring the response.

const response = await fetch(...);
const text = await response.text();
console.log(text); 

If you want to render the whole page again, then don't use Ajax. Just use a regular form submission.

(And put the search parameter in the query string instead of a custom header).

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