【问题标题】:Updating html value without page reload在不重新加载页面的情况下更新 html 值
【发布时间】:2016-01-14 16:17:06
【问题描述】:

如何在不重新加载整个页面的情况下更新 ejs 对象?我通过 jquery 从服务器获取数据,但是我不知道如何在 ejs 模板中将 title 对象从 Express 更新为 NewTitle。顺便说一句,如果有人知道可以帮助快速 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");
});

【问题讨论】:

    标签: javascript jquery node.js express


    【解决方案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()

    【讨论】:

    • 是否需要在span中放入需要的html标签?
    • 你可以使用任何你想要的,但你需要找到要更改的元素(包含标题的那个)
    • 您能否将我链接到对菜鸟友好的资源/网站/视频,并让我通过示例学习 express 节点 js?我是一名移动开发人员,对服务器端开发一无所知,所以我问
    • 太多了,不知道你有什么用,这方面谷歌会比我更好的帮助你。
    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 2017-08-13
    • 2010-12-22
    • 2021-07-17
    • 1970-01-01
    • 2011-10-02
    • 2020-10-04
    相关资源
    最近更新 更多