使用Ajax和Nodejs更新页面上的数据

时间:2017-06-01 18:39:10

标签: javascript ajax express

我正在尝试编写一个循环来每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(&#34; /&#34;)和ajax请求,我得到了

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

因为我试图两次发送数据

我应该如何修改代码,这样才能看到我的数据显示在&#39; http://localhost:3000/&#39;它每30秒更新一次?

谢谢。

2 个答案:

答案 0 :(得分: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);
});

答案 1 :(得分:0)

像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>