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('\r\n');
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
语法错误
syntax error
在第二行代码我收到错误
On the 2nd line of code I get the error
data.split不是函数
data.split is not a function
我做错了什么?
ETA 根据firebug控制台,responseText如下:
ETA According to the firebug console, the responseText is the following:
2009,0,2,29.0000 \r\\\
2009,... \r\\\
2011,10,30,494.3500\r\\ \\ n
2009,0,2,29.0000\r\n2009,...\r\n2011,10,30,494.3500\r\n
ETA 我在将数据分成几行之前添加了数据提醒,得到以下结果:
ETA I added an alert of the data before I try splitting it into lines, and I get the following:
[Object XMLDocument]
[Object XMLDocument]
推荐答案
我相信你误解了jQuery.get()假设要使用的。
I believe you misunderstand what jQuery.get() is suppose to be used for.
从它的文档页, ...使用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('\n');
});
EDIT ::
由于您说数据正在加载,请尝试此小提琴。它的工作很好。
: Since you say the data is being 'loaded' properly, try this fiddle. It works just fine.
EDIT2 ::
洞察力。当它拉取.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('\n');
},dataType='text');
这应该将返回的数据放入正确的字符串格式。
This should put the returning 'data' into the proper string format.
这篇关于jQuery获取CSV文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!