简体   繁体   English

d3.js使用函数作为csv源而不是csv路径

[英]d3.js use a function as csv source instead of a csv path

I'm new to d3.js, when loading data, examples I've seen so far looks like 我是d3.js的新手,在加载数据时,到目前为止我看到的示例看起来像

d3.csv("path/to/file.csv")...

I have a function that returns a dynamic server side generated csv, i use synchronous POST ajax to generate them, but for simplicity's sake lets say, I have a js function like this 我有一个返回动态服务器端生成的csv的函数,我使用同步POST ajax生成它们,但是为了简单起见,可以说,我有一个类似js的函数

function makeCSV(){
    return "id,value\n"+
           "0,value 1\n"+
           "1,value 2\n"+
}

is there a way to do something like this? 有没有办法做这样的事情? and is this approach recommended at all (synchronous ajax is sure to cause lag) 并且完全建议使用此方法(同步ajax肯定会导致延迟)

d3.csv(makeCSV())...

other related concerns about CSV data loading is, is it required that .csv file is served, or would it be possible to simply put URL that makes and downloads a dynamically generated csv file, this could work as a replacement for AJAX call but manually encoding each parameter looks tedious and non-dynamic 与CSV数据加载有关的其他相关问题是,是否需要提供.csv文件,还是可以简单地放置用于生成和下载动态生成的csv文件的URL,这可以代替AJAX调用,但可以手动编码每个参数看起来乏味且非动态

d3.csv("?action=makeCSV&param1=val1&param2=val2")...

According to the spec d3.csv() requires the first argument be the url to load the CSV from. 根据规范d3.csv()要求第一个参数是从中加载CSV的网址。 If you want to just parse a string containing your CSV's content no matter how this was created, you need to use d3.csv.parse() instead. 如果您只是想解析包含CSV内容的字符串,无论它是如何创建的,都需要使用d3.csv.parse()来代替。 For your code this would be some like this 对于您的代码,这将是这样的

var rows = d3.csv.parse(makeCSV());

 function makeCSV(){ return "id,value\\n"+ "0,value 1\\n"+ "1,value 2\\n"; } var rows = d3.csv.parse(makeCSV()) console.log(rows); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM