我对Ajax调用一无所知,已经读了几个小时了,但是所有的教程都提到了load方法和一个像click这样的监听器。
我有一个函数(drawThreat),它在我的svg上添加了一些图标(fontawesome),有一个包含大量x和ys的json文件,我所需要做的就是让一个ajax调用来运行这个函数,每5秒运行json文件中的所有x和ys,并更新页面上的svg元素。以下是功能:
function drawThreat (x, y){
var canvas = d3.select("#map")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.attr("id", "Threat");
var Threat = canvas.append('svg')
.append('text')
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'central')
.attr("x", x)
.attr("y", y)
.attr("class", "threat")
.style('font-family','FontAwesome')
.style('font-size','20px')
.style('fill', 'red')
.text(function (d) {
return '\uf2be'
});
return Threat
};任何帮助都将不胜感激:)即使它是与问题相关的教程的链接。到目前为止,我看了6到7个教程,没有运气。
发布于 2017-07-12 00:12:49
如果我正确理解了您的需要,您基本上可以有一个类似于下面的代码:
var dataFileUrl = "url-to-your.json"; // assign the url to a variable
var canvas = d3.select("#map") // get a ref from the SVG element
.append("svg") // you might want to define it only one time
.attr("width", 500)
.attr("height", 500)
.attr("id", "Threat");
var updateInterval = setInterval(function(){
d3.json(dataFileUrl , function (jsonData) { // AJAX call
drawThreat(jsonData); // calls main function
});
},5000); // every 5 * 1000ms
function drawThreat (jsonData){
canvas.selectAll('text.threat').remove(); // makes sure we don't have old icons
canvas.selectAll('text')
.data(jsonData) // for each set in json
.enter()
.append('text') // create a text and append it to svg canvas
.attr("class", "threat") // with class of threat
.attr("x", function (d) { return d[0]; }) // first element of each set
.attr("y", function (d) { return d[1]; }) // second element of each set
.text('\uf2be');
};为了减少js代码,我建议使用CSS添加样式和属性:
.threat{
text-anchor:middle;
dominant-baseline:central;
font-family:FontAwesome;
font-size:20px;
fill:red;
}您还可以在这里看到它的作用:https://codepen.io/FaridNaderi/pen/awPBwm
希望它能帮助你明白重点。
https://stackoverflow.com/questions/45043265
复制相似问题