简体   繁体   中英

How to update ejs file with fetch? Using node.js and javascript

I am trying to update an ejs file. What I am trying to do is simply to change the text in the h1 tag with the data from a get request sent with fetch. But nothing happens. If I type in the url path in the browser everything works fine, but when using fetch the server gets the data, but nothing is changing on the page.

My guess is that this has to do with using the fetch method? Is that correct? Is it not possible to use fetch? If so, how do you do it instead?

Here is my code:

Ejs:

<input type="text" id="surveyName" placeholder="Name your survey">
<div id="addQuiz" onclick="newQuiz()">Add</div>
<h1>Survey: <%= data.userQuery %></h1>

The fetch get request:

const newQuiz = () => {
    const name = document.getElementById("surveyName").value

    fetch(`/${name}`)
    .then((data) => {
        alert('sent!')
    })}

Routing in node:

app.get("/:userQuery", (req, res) => { 
  console.log(req.params.userQuery)
  res.render('home',{data: {userQuery: req.params.userQuery}}) 
}); 

If you want to load the response to the HTTP request as a whole new page then don't use Ajax . The whole point of Ajax is that it makes a request with JavaScript and makes the response available to JavaScript without navigating to a new use.

Use a regular HTML form submission instead.


If you want to use Ajax then you need to use a body interface method to deal with the response body and then use that data to manipulate the existing document . If you do that then you'll probably be better off making the request to an endpoint that returns the data as JSON and not one that injects it into an EJS template. You might want to read MDN's guide to using fetch .

See if this works for you-
Ejs:

<input type="text" id="surveyName" placeholder="Name your survey">
<div id="addQuiz" onclick="newQuiz()">Add</div>
<h1 id="some_id">Survey: <%= data.userQuery %></h1>

The fetch get request:

const newQuiz = () => {
    const name = document.getElementById("surveyName").value;

    fetch(`/${name}`)
    .then((data) => {
        alert('sent!');
        document.querySelector("#some_id").innerHTML = data.userQuery;
    })}

Routing in node:

app.get("/:userQuery", (req, res) => { 
    res.json({userQuery: req.params.userQuery});
}); 

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