所以我有这个csv文件(csv文件最好可能位于服务器端,但尚未决定)。很可能会向用户显示从下拉菜单中选择这些csv文件的选项。然后在选择特定文件后,用户单击“输入”,然后应该在javascript中将此选定的csv文件作为数组读取。那怎么办? : -
我的问题是How to pass variables and data from PHP to JavaScript?
___ csv_file ____
Class, Subclass, Company, Product,
Chocolate, Wafer chocolate, Nestle, KitKat,
Chocolate, White chocolate, Nestle, Milkybar,
Chocolate, White chocolate, Nestle, Milkybar,
Chocolate, Caramel chocolate, Nestle, BarOne,
Chocolate, Milk chocolate, Nestle, Nestle Milk chocolate,
Chocolate, Milk chocolate, Nestle, Nestle Milk chocolate,
Chocolate, Milk chocolate, Nestle, Nestle Milk chocolate,
Chocolate, Milk chocolate, Nestle, Nestle Milk chocolate,
Chocolate, Milk chocolate, Cadbury, Dairy milk,
为了手动阅读,这就是已经完成的工作。但正如你所看到的那样,所有的csv_data都是硬编码的,但我想让它自动化(即通过读取csv文件生成)
root = {
"name": "Chocolate", "tag":"class",
"children": [
{
"name": "Wafer", "tag":"subclass",
"children": [
{
"name": "Nestle", "tag":"company",
"children": [
{"name": "KitKat", "tag":"product"}
]
}
]
},
{
"name": "White", "tag":"subclass",
"children": [
{
"name": "Nestle", "tag":"company",
"children": [
{"name": "Milkybar", "tag":"product"}
]
}
]
},
{
"name": "Caramel", "tag":"subclass",
"children": [
{
"name": "Nestle", "tag":"company",
"children": [
{"name": "BarOne", "tag":"product"}
]
}
]
},
{
"name": "Milk", "tag":"subclass",
"children": [
{
"name": "Nestle", "tag":"company",
"children": [
{"name": "Nestle Milk", "tag":"product"}
]
}, {
"name": "Cadbury", "tag":"company",
"children": [
{"name": "Dairy Milk", "tag":"product"}
]
}
]
}
]
};
现在的问题是我希望javascript只是从本地位置读取这个csv文件。但是有可能在JAVASCRIPT中将CSV文件读入这样一个复杂的维数组吗?
答案 0 :(得分:1)
可能的设置:
PHP Web服务器(或NodeJS服务器 - 我个人最喜欢的)
可能的工作流程:
答案 1 :(得分:1)
首先在服务器上创建一个PHP文件,为它提供一个相关的名称,如candyData.php,你可以在其中:
//code to read your data.csv
//code which stores the data from the csv into an object $candyData
$json = json_encode($candyData);
return $json
然后在客户端使用Javascript,我也将使用JQuery:
jQuery.ajax({
url: "http://example.mysite.com/rest/candyData.php",
type: "GET",
success: function (response) {
var candyData = response;
//Here you'd put all the code you currently have so you can visualize the data
},
error: function (response) {
console.log("failed");
}
});