数据更改时,D3.js表未刷新

时间:2015-09-21 06:44:13

标签: javascript json d3.js

我使用d3.json函数在浏览器中显示表格。当json文件中的数据发生更改时,浏览器中的表格不会刷新。它显示的是先前的数据,而不是表格中的新数据。如果我在浏览器中手动刷新,那么它可以正常工作,表格会随新数据而变化。

以下是我使用的代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

td{ 
    padding:7px; border:#4e95f4 1px solid;
}

/* provide some minimal visual accomodation for IE8 and below */
th{
    background: #dae5f4;
    border: 1px solid black;
        padding: 2px 4px;
        font-weight: bold;
}

/*  Define the background color for all the ODD background rows  */
tr:nth-child(odd){ 
    background: #b8d1f3;
}

/*  Define the background color for all the EVEN background rows  */
tr:nth-child(even){
    background: #dae5f4;
}

a
{
position: absolute;
}

</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<div id="container"></div>
<a href="http://192.168.7.102:3000/data/traffic" download="">Download</a>
<script>

var jsonURL = "http://192.168.7.102:3000/data/traffic";

d3.json(jsonURL, function(data) {
    // the columns you'd like to display
    var columns = ["Clients", "Traffic", "Rank"];

    var table = d3.select("#container").append("table")
        .style("margin-top", "50px")
            .style("margin-left","280px")
            .style("border-collapse", "collapse")         // <= Add this line in.
            .style("border", "2px black solid")
            .style("width", "50%"),
        thead = table.append("thead"),
        tbody = table.append("tbody");

    // append the header row
    thead.append("tr")
        .selectAll("th")
        .data(columns)
        .enter()
        .append("th")
            .text(function(column) { return column; });

    // create a row for each object in the data
    var rows = tbody.selectAll("tr")
        .data(data)
        .enter()
        .append("tr");

    // create a cell in each row for each column
    var cells = rows.selectAll("td")
        .data(function(row) {
            return columns.map(function(column) {
                return {column: column, value: row[column]};
            });
        })
        .enter()
        .append("td")
            .text(function(d) { return d.value; });
});
</script>  

当json文件中的数据发生更改时,图表不会刷新。 有没有人对问题在哪里有任何想法?

我创建了node.js应用程序和restful web服务,根据用户需求从数据库中获取数据,并将数据写入&#34; traffic.json&#34;文件。当用户在应用程序上选择特定图表时,我们将该html文件发送到浏览器。在HTML d3.json中,函数正在触发。

Here is the code I use:
=======================
 var express = require('express'),
 http = require('http'),
 querystring = require('querystring'),
 router = express.Router(),
 fs = require('fs'),
 MongoClient = require('mongodb').MongoClient,
 format = require('util').format,
 mongo = require('mongodb'),
 monk = require('monk'),
 json2csv = require('json2csv'),
 Reloader = require('reload-json'),
 reload = new Reloader();

var Start_Date ;
var End_Date ;
var Client_Ip;
var Clientip;
var ChooseData;
var Charts;
var Chart1;
var Choosedata1;
//Getting the data from calsoftlabs page
router.post('/myaction', function(req, res, next) {

     Start_Date =   req.body.StartDate +'T'+ req.body.StartTime ;
     End_Date   =   req.body.EndDate +'T'+ req.body.EndTime;
     Client_Ip  =   req.body.ClientIP;
     Clientip   =   req.body.ClientIPS;
     ChooseData =   req.body.ChooseData;
     Charts     =   req.body.Charts;
     Chart1     =   req.body.Chart;
     Choosedata =   req.body.Data;

//converting date and time to timestamp.
function evaldate(input){
var date = new Date(input);
return date.getTime();
}

var Start_timestamp = evaldate(Start_Date),

 End_timestamp = evaldate(End_Date);


var dbdata,
 start_time,
 end_time,
 client_ip,
 choosedata,
 options,
 data,
 req;
//sending parameters to restfull webapp service
if(Choosedata == "upload" || Choosedata == "download") {
 data = querystring.stringify({
      start_time: Start_timestamp,
      end_time: End_timestamp,
      client_ip: Clientip,

    });
} else if(ChooseData == "upload_traffic" || ChooseData == "download_traffic" || ChooseData == "both" ) {

data = querystring.stringify({
      client_ip: Client_Ip,
    });

}
console.log(data);

if(ChooseData == "upload_traffic") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/upload_traffic',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

} else if(ChooseData == "download_traffic") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/download_traffic',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};


} else if(Choosedata == "upload") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/upload',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

}else if(Choosedata == "download"){

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/download',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

} else if(ChooseData == "both") {

options = {
    host: 'localhost',
    port:8080,
    path:'/restful/traffic/both',
    method:'POST',
     headers: {
        'Content-Type': 'application/json',
    }
};

}

//creating file, writing network data to a file.
var fileName = 'views/traffic.json';
req = http.request(options, function(response) {
 var jsonString = '';
 response.on('data', function(data) {
    jsonString += data;
}); 
 response.on('end',function(){
    console.log(jsonString);
    fs.writeFile(fileName, jsonString,'utf-8'); 
    });
});

if(Chart1 == 'Line') {

  res.sendfile('views/Line.html');

} else if(Chart1 == 'Bar') {

res.sendfile('views/Newbar.html');

} else if(Chart1 == 'Area') {

res.sendfile('views/Area.html');

} else if(Chart1 == 'Pie') {

res.sendfile('views/Pie.html');

} else if(Chart1 == 'Multiline') {

res.sendfile('views/Multiline.html');

} else if(Chart1 == 'All') {

res.sendfile('views/Newall.html');

} else if(Charts == 'Table') {

res.sendfile('views/Table.html');

} else if(Charts == 'StackedBar') {

res.sendfile('views/StackedBar.html')

}

req.write(data);
req.end();
req.on('error', function(e) {
    console.error(e);
});
});

module.exports = router;

1 个答案:

答案 0 :(得分:0)

您的表格未刷新,因为您的d3.json(jsonURL, function(data) {...})未收听数据文件的更改。该功能将运行一次,就是这样。

假设您在某个时间间隔内重新运行数据函数d3.json(jsonURL, function(data) {...}),那么下一个问题就是您永远不会更新您的表格,只需添加一个新表格:

var table = d3.select("#container").append("table")

您没有选择您的表(可能已经存在),而只是将新表附加到DOM。您需要查看data binding principle in d3