[英]Loading Values of a JSON to JavaScript
我找不到下面列出的代碼有什么問題。 它不會將values.json的值加載到變量statusau中。 如果我document.write(JSON.stringify(statesau))我得到{}
values.json的內容是
{
"values": {
"New South Wales": 8,
"Victoria": 6,
"Queensland": 3,
"South Australia": 7,
"Western Australia": 4,
"Tasmania": 6,
"Northern Territory": 7
}
}
HTML代碼在這里:
<!DOCTYPE html> <html> <head> <title>Wave to GeoJSON</title> <script src="http://d3js.org/d3.v2.js" charset="utf-8"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <style type="text/css"> #states path { stroke: #fff; } </style> </head> <body> <h1>Wave to GeoJSON</h1> <script type="text/javascript"> var statesau={}; $.getJSON('values.json', function(data) { statesau=data; }); document.write(JSON.stringify(statesau)); var w = 960, h = 500; var z = d3.scale.category10(); var fill = d3.scale.log() .domain(d3.extent(d3.values(statesau))) .range(["brown", "steelblue"]); var projection = d3.geo.azimuthal() .origin([135, -26]) .translate([250,180]) .scale(700); var path = d3.geo.path() .projection(projection); var svg = d3.select("body").append("svg") .attr("width", w) .attr("height", h); var states = svg.append("g") .attr("id", "states"); d3.json("au-states.json", function(collection) { states.selectAll("path") .data(collection.features) .enter().append("path") .attr("fill", function(d) { return fill(statesau[(d.properties["STATE_NAME"])]); }) .attr("d", path); }); </script> </body> </html>
當您具有getJSON
類的異步功能時,您需要重新getJSON
代碼。
<!DOCTYPE html>
<html>
<head>
<title>Wave to GeoJSON</title>
<script src="http://d3js.org/d3.v2.js" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">
#states path {
stroke: #fff;
}
</style>
</head>
<body>
<h1>Wave to GeoJSON</h1>
<script type="text/javascript">
var statesau={};
$.getJSON('values.json', function(data) {
statesau=data;
restOfCode();
});
function restOfCode(){
document.write(JSON.stringify(statesau));
var w = 960,
h = 500;
var z = d3.scale.category10();
var fill = d3.scale.log()
.domain(d3.extent(d3.values(statesau)))
.range(["brown", "steelblue"]);
var projection = d3.geo.azimuthal()
.origin([135, -26])
.translate([250,180])
.scale(700);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h);
var states = svg.append("g")
.attr("id", "states");
d3.json("au-states.json", function(collection) {
states.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("fill", function(d) {
return fill(statesau[(d.properties["STATE_NAME"])]);
})
.attr("d", path);
});
}
</script>
</body>
</html>
正如webdeb在他的評論中提到的那樣,主要問題是$.getJSON
是一個異步函數。 如果您希望document.write正常運行,則必須將其添加到回調中,如下所示:
$.getJSON('values.json', function(data) {
statesau=data;
document.write(JSON.stringify(statesau));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.