jQuery 获取 CSV 文件时出错 [英] Error with jQuery get of a CSV file
问题描述
这是我的相关 jQuery 代码:
Here is my relevant jQuery code:
$.get('sampleData.csv', function(data) {
var lines = data.split('
');
sampleData.csv 文件的前几行如下所示:
The first few line of the sampleData.csv file look like this:
2009,0,2,29.0000
2009,0,6,655.6200
2009,0,2,29.0000
2009,0,6,655.6200
我收到 2 个错误.在 csv 文件的第一行出现错误
I get 2 errors. On the first line of csv file I get the error
语法错误
在第二行代码中出现错误
On the 2nd line of code I get the error
data.split 不是函数
data.split is not a function
我做错了什么?
ETA 根据萤火虫控制台,responseText 如下:
ETA According to the firebug console, the responseText is the following:
2009,0,2,29.0000 2009,... 2011,10,30,494.3500
2009,0,2,29.0000 2009,... 2011,10,30,494.3500
预计到达时间 我在尝试将数据拆分成行之前添加了数据警报,结果如下:
ETA I added an alert of the data before I try splitting it into lines, and I get the following:
[对象 XMLDocument]
[Object XMLDocument]
推荐答案
我相信你误解了 jQuery.get() 的用途.
I believe you misunderstand what jQuery.get() is suppose to be used for.
从它的 doc page, "...从服务器加载数据使用 HTTP GET 请求...."
对文件执行 $.get() 不会将该文件的数据转换为可以使用的结构.您必须通过一个服务器来请求它,然后该服务器将提供 .csv 数据......它应该类似于以下内容
Doing a $.get() on a file will not get you that file's data into a structure that can be used. You have to request this through a server which will then provide the .csv data ... it should look something like the following
$.get('http://url.to.server.page',function(data){
var dataStr = new String(data);
var lines = dataStr.split('
');
});
<小时>
:既然你说数据被正确加载"了,试试这个fiddle.它工作得很好.
: Since you say the data is being 'loaded' properly, try this fiddle. It works just fine.
:
您的上次编辑提供了一些有趣的见解.当它提取 .csv 文件时,它会将其转换为 XML 与文本类型.请尝试以下操作:
Your last edit gave some interesting insight. When it pulls the .csv file, its converting it to a type of XML vs text. Try the following:
$.get('http://url.to.server.page',function(data){
var dataStr = new String(data);
var lines = dataStr.split('
');
},dataType='text');
这应该将返回的数据"转换为正确的字符串格式.
This should put the returning 'data' into the proper string format.
这篇关于jQuery 获取 CSV 文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!