Read Local File Text (tab Separated Values) With D3 Or Ajax Cause Syntax Error In Firefox Development Console
Solution 1:
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be usedfunctiondoOpen(evt) {
var files = evt.target.files,
reader = newFileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script><inputtype="file"id="openselect" /><textareaid="showresult"></textarea>
Solution 2:
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy urlvar jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><preid='data'></pre>
Post a Comment for "Read Local File Text (tab Separated Values) With D3 Or Ajax Cause Syntax Error In Firefox Development Console"