简体   繁体   English

如何使用 fetch 更新 ejs 文件? 使用 node.js 和 javascript

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

I am trying to update an ejs file.我正在尝试更新 ejs 文件。 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.我想要做的只是用 fetch 发送的 get 请求中的数据更改 h1 标记中的文本。 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.如果我在浏览器中输入 url 路径,一切正常,但使用 fetch 时服务器获取数据,但页面上没有任何变化。

My guess is that this has to do with using the fetch method?我的猜测是这与使用 fetch 方法有关吗? 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 .如果要将对 HTTP 请求的响应加载为一个全新的页面,请不要使用 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. Ajax 的全部意义在于它向 JavaScript 发出请求,并将响应提供给 JavaScript而无需导航到新用途。

Use a regular HTML form submission instead.请改用常规的 HTML 表单提交。


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 .如果你想使用 Ajax 那么你需要使用body 接口方法来处理响应体,然后使用该数据来操作现有文档 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.如果您这样做,那么您最好向一个端点发出请求,该端点将数据返回为 JSON 而不是将其注入 EJS 模板的端点。 You might want to read MDN's guide to using fetch .您可能想阅读MDN 的 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});
}); 

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

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