javascript - 更新 html 值而不重新加载页面

标签 javascript jquery node.js express

如何在不重新加载整个页面的情况下更新 ejs 对象?我通过 jquery 从服务器获取数据,但是我不知道如何将 title 对象从 Express 更新为 NewTitle在 ejs 模板中。顺便说一句,如果有人知道可以帮助 Express Nodejs 初学者的好资源,请提及。

index.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1 id="pageTitle"><%= title %></h1>
    <p>Welcome to <%= title %></p>

    <script type = "text/javascript"
            src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <script type = "text/javascript" language = "javascript">
      $(document).ready(function() {

      $(document).ready(function() {
        $("#myButton").bind('click', function() {

          event.preventDefault();
          var data = $('#myEditText').val();
          var result = $.post('/yolo', {textBoxValue: data}, function(callback) {
            alert("data: "+ callback.title);
              $(document).ready(function(){
                  title = callback.title;
              });
          });

        });
      });

    </script>
  </body>
</html>

index.js:

router.post('/yolo', jsonParser, function(req, res, next) {

    res.send('index', { title: 'NewTitle'})
    console.log("hello inside index.js method 1");
});

最佳答案

您无法通过 Jquery 更新 Ejs 变量,您应该使用如下内容:

HTML

<p>Welcome to <span class="title"><%= title %></span></p>

JS:

[...]
var result = $.post('/yolo', {
    textBoxValue: data
}, function(callback) {
    alert("data: " + callback.title);
    $(document).ready(function() {
        $('.title').html(callback.title);
    });
});
[...]

并且您必须在 Node.js 中使用 res.json({title: 'NewTitle'}) 而不是 res.send()

关于javascript - 更新 html 值而不重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794434/

相关文章:

node.js - 在 stripe 中调用函数时, "comma"语法是什么意思?

node.js - Node.js 的内部结构。它实际上是如何运作的

javascript - 每次显示警报时都会增加 sessionStorage 值

javascript - 单击标签应选择 radio 输入

javascript - js中数组从零开始递增

javascript - 添加视频链接并在我的网页中播放视频

javascript - 如何在调用事件后延迟执行函数?

node.js - 当我尝试使用 npm 在 win8 中安装某些软件包时,它总是给我这样的错误

javascript - 使用带有 Rails 的 React Datepicker 遇到问题

javascript - 如何使用 Angular 2+ 循环对象键并在表格中显示