Error with jQuery get of a CSV file

[亡魂溺海] 提交于 2019-11-29 11:37:59

I believe you misunderstand what jQuery.get() is suppose to be used for.

From it's doc page, "...Load data from the server using a HTTP GET request...."

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::

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 code:

$.get('data.csv', function(data) {
  var lines = data.split('\r\n');
});

works until jquery version 1.5.
From version 1.5 callback function in get() method is passed "jqXHR" object, not "XMLHttpRequest" object.
Code can be changed to:

$.get('data.csv', function(data) {
  var lines = data.split('\r\n');
}, "text");

Then it will work.

http://api.jquery.com/jQuery.get/

Your almost there. Missing the final parenthesis and need a different split character.

$.get('sampleData.csv', function(data) {
var lines = data.split(',');
});

Edit

Ah you changed your CSV to two lines i assumed it was just one line seperated by commas not data seperated by new line also seperated by commas. The below I retested and worked fine for me.

<html>
<head>
<script type="text/javascript">Jquery Reference or insert directly here </script>
</head>
<body>
<script>
$(document).ready(function(){

    $.get('csv.csv', function(data) {
    // Split the lines
    var lines = data.split('\n');
    var i = 0;

    for(i=0; i<lines.length; i++)
    {
       alert(lines[i]);
    }

}); 

});
</script>
</body>

</html> 

I just had that html file on my desktop with the csv you pasted in the same place.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!