I have a CSV file hosted on a remote server. Is there a way for jQuery to consume that file so it can be converted to a jQuery array? Would I still be facing cross-site scripting problems?
3 Answers
You'll be running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will always (but for very very rare exceptions) fail, no matter what the content is.
You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.
Consuming the CSV itself is rather trivial:
csv_arr = csvstring.split(/\n/);
$.each(csv_arr, function(i,e){
csv_arr[i] = e.split(',');
});
Edit: Caution, as @echoback mentioned, I have missed the possibility of quoted values.
Luckily, there's an awesome plugin that turns CSV into JSON. Just like that.
3 Comments
wersimmon
Remember to consider quoted strings.
"hello, world", 1234 is two elements, not three.vzwick
@echoback Thanks, I had missed that. Updated the answer accordingly.
Jorge Orpinel Pérez
csonv.js doesn't seem to work properly for me (on Firefox). I'm going to try D3: learnjsdata.com/read_data.html