【问题标题】:Use Ajax and Nodejs to update data on a page使用 Ajax 和 Nodejs 更新页面上的数据
【发布时间】:2017-06-01 18:39:09
【问题描述】:

我正在尝试编写一个循环来每 30 秒更新一次网页,但我不确定如何使用 setInverval 函数进行 ajax 调用。这是我的服务器代码:

var app = express()
app.get('/', function(req, res){
// error here
res.sendFile('./index.html',{root: __dirname})
//...Some data 
res.send(data)
});

我的 index.html 中有一个 setInverval 函数:

<script>
function ajaxCall(){
  $.ajax({url: "http://localhost:3000/", success: function(result){
    // I want to receive new result every 30 seconds
  }})

}
setInterval(ajaxCall,30000)
</script>

由于我不确定如何处理 app.get("/") 和 ajax 请求,所以我得到了

Error: Can't set headers after they are sent.

因为我尝试发送数据两次

我应该如何修改代码,以便我可以看到我的数据显示在“http://localhost:3000/”上并且每 30 秒更新一次?

谢谢。

【问题讨论】:

    标签: javascript ajax express


    【解决方案1】:

    Can't set headers after they are sent 通常表示您两次响应请求

    你不能那样做。

    对于每个request/req,应该只有一个response/res

    app.get('/', function(req, res) {
      // you respond to the request here
      res.sendFile('./index.html',{root: __dirname});
      // and you respond again here
      res.send(data)
    });
    

    决定是否要为该端点使用sendFile()send(data)

    从您的代码来看,您可能想要创建 另一个 端点,以使用您的 AJAX 调用,后者在哪里进行

    // serve your index
    app.get('/', function(req, res) {
      res.sendFile('./index.html',{root: __dirname})
    });
    
    // serve your data
    // Your AJAX call should hit this endpoint instead
    app.get('/data', function(req, res) {
      var data = 'lorem ipsum dolor';
      res.send(data);
    });
    

    【讨论】:

    • 谢谢,我知道这是个问题。如果我想发送数据并删除 sendFile(),我的网页会在每次刷新时更新,但永远不会调用 setInterval 函数。
    【解决方案2】:

    就像 Nicholas Kyriakides 所说,您需要定义以下内容:

    // serve your index
    app.get('/', function(req, res){
      res.sendFile('./index.html',{root: __dirname})
    });
    
    // serve your data
    // Your AJAX call should hit this endpoint instead
    app.get('/data', function(req, res) {
     var data = "lorem ipsum dolor";
      res.send(data);
    });
    

    然后,您需要更改您的 AJAX 调用:

    <script>
    function ajaxCall(){
      $.ajax({url: "http://localhost:3000/data", success: function(result){
        //do whatever you want with the returned data (in result)
        //f.e. to update something on your web page, you want something like:
        document.getElementById("idOfElementYouWantChanged").innerHTML = result;
      }})
    
    }
    setInterval(ajaxCall,30000)
    </script>
    

    【讨论】:

    • 除了获得一些神奇的互联网积分之外,公然复制/粘贴我的答案有什么好处?
    • 我已经在回答了,看到你也回答了,看来他还是不明白这个概念,所以我想给他一个完整的例子。对不起,如果我伤害了你的“神奇的互联网点”的感觉。我只是来帮忙的。
    • 两个答案都有帮助,Ajax 调用部分可以解决问题,但由于 nicholas 先回答...
    • 没问题,就像我说的那样,我完全不在乎 :) 祝你工作顺利!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2019-12-11
    • 2016-04-14
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多