简体   繁体   English

使用setTimeout节点玉表达动态更新内容

[英]dynamically update content with setTimeout node jade express

hello I am new to node and would like to have html content update dynamically every say second. 你好,我是node的新手,想让html内容每秒动态更新。 I am able to update a value with set timeout the following way, however I must refresh the page in order to see the change 我可以通过以下方式使用设置的超时值更新值,但是我必须刷新页面才能看到更改

var jade = require('jade');
var fs = require('fs');
var express = require('express');
var app = express();

function getName(currentName) {
    return currentName + " more hello world ";
}

function updateApp(data) {

    data.name = getName(data.name); // get desired text
    app.get('/', function(req, res){
        res.render("index", {data: data});
    });
    setTimeout(function() {updateApp(data)}, 1000); // schedule values update
}

app.set('views', __dirname+'/views');
app.set('view engine', 'jade');


var startValue = "hello world"
var data = {
    name: startValue
}
//start app
updateApp(data);

app.listen(3000);

where 哪里

html
    head
        script(type='text/javascript').
            var data = !{data};
    body
        h1 
            text= data.name

is my jade template. 是我的玉模板。 Is there a simple way to change this so that the updated text is displayed without a page refresh? 有没有简单的方法可以更改此设置,以便显示更新的文本而无需刷新页面?

Click here for my JSFiddle 点击这里查看我的JSFiddle

function loadXMLDoc(url, method, callback) {
    var xmlhttp = window.XMLHttpRequest?xmlhttp=new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange=function() {
          if (xmlhttp.readyState==4) {
              if(xmlhttp.status==200) {
              callback(xmlhttp.responseText);
              } else callback(false);
          }
      }
    xmlhttp.open(method,url,true);
    xmlhttp.send();
    }

var UpdateAlgo = function() {
    loadXMLDoc("http://ajax-url-here/", "POST",
        function(result) {
            if(result !== false) {
            document.getElementById("myDiv").innerHTML = result;
            }
        AfterUpdate();
        });
    }

var AfterUpdate = function() {
    window.setTimeout(function() {
        UpdateAlgo();
        }, 1000);
    }

AfterUpdate();

I think you should be able to learn a bit from this 我认为您应该可以从中学到一些东西

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

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