简体   繁体   English

如何在不重新加载页面即可生效的情况下应用此AJAX请求?

[英]How I can apply this AJAX request without reloading the page to take effect?

This is a to-do app. 这是一个待办事项应用程序。 Whenever I click on "Add" it needs to reload the page so that it takes effect and you can actually see the items. 每当我单击“添加”时,它都需要重新加载页面,以使其生效,并且您实际上可以看到这些项目。

I want to make the request AJAX where it doesn't need to refresh the page. 我想在不需要刷新页面的地方发出请求AJAX。 How I can do that? 我该怎么做?

I use Express for servers, EJS for view engine. 我将Express用于服务器,将EJS用于视图引擎。

This is Server stuff for the app: 这是该应用程序的服务器内容:

let items = [];
module.exports = function(app, urlencoded) {
  app.get("/todo", function(req, res) {
    res.render("toDo", { data: items });
  });
  app.post("/todo", urlencoded, function(req, res) {
    items.push(req.body);
    console.log(req.body);
  });
  app.delete("/todo:item", function(req, res) {});
};

This is the script that I use it to send an AJAX request: 这是我用来发送AJAX请求的脚本:

let btn = document.querySelector("button");
let itemValue = document.querySelector("input").value;
btn.addEventListener("click", function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/todo", true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(
    JSON.stringify({
      item: itemValue
    })
  );
});

And this is the HTML(EJS) file: 这是HTML(EJS)文件:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>To-do Application</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="../Public/Assets/Styles.css" />
  <script src="../Public/Scripts/Add.js" defer></script>
</head>
<body>
  <div id="todo-table">
    <form onsubmit="return false;">
      <input type="text" name="item" placeholder="Write an item here" required>
      <button id="Add">Add</button>
    </form>
    <ul>
      <% data.forEach(function(element){ %>
        <li> <%= element.item %> </li>
      <% }) %>
    </ul>
  </div>
</body>
</html>

I fixed the problem. 我解决了这个问题。 I just made the <li> myself when the request successes then I loaded them when the page gets ready. 当请求成功时,我自己创建了<li> ,然后在页面准备就绪时加载了它们。 I also removed the data thing for ejs as I found them the problem since they only render when the page gets refreshed/loaded, next time I will use something much more interactive and realtime like Vue/React. 我还删除了ejs的数据对象,因为我发现了它们的问题,因为它们仅在刷新/加载页面时才呈现,下次,我将使用诸如Vue / React之类的更具交互性和实时性的东西。

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

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