带路径的JS $ .get方法文件 [英] JS $.get method file with path
问题描述
我想从用户可以选择的路径加载一个* .csv 文件。
我得到的路径: C:\\ Users \\ ...
I want to load a *.csv file from a path wich the user can choose.
The path I get: C:\\Users\\...
但是 $。get
方法不能读取此路径。
But the $.get
method can't read this path. How does the path have to look like?
$.get(pathAndFile, function (data) {...
推荐答案
如果您想通过计算机从JavaScript读取CSV数据,需要指导用户选择文件(这是没有办法的,除了病毒可能是例外),但是一旦用户选择了一个文件,你就可以用少量的JavaScript读取和解析CSV数据(< a href =http://jsfiddle.net/V33C6/ =nofollow> demo )
If you wanted to read CSV data in JavaScript from a computer you would need to instruct the user to select the file (there is no way around this, with the possible exception of a virus). However once a user selected a file you can read and parse CSV data with a small amount of JavaScript like this (demo)
使用这个HTML:
<input type="file" id="file" name="file" />
<table id="rows"></table>
此JavaScript:
And this JavaScript:
var output = $('#rows');
$('#file').on('change', function(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
// Only process text files.
if (!f.type.match('text/.*')) {
alert('Unsupported filetype:'+f.type);
continue;
}
var reader = new FileReader();
reader.onloadend = function(evt) {
var rows, row, cols, col, html;
if (evt.target.readyState == FileReader.DONE) {
output.empty();
rows = evt.target.result.match(/[^\r\n]+/g);
for(row = 0; row < rows.length; row++) {
cols = rows[row].split(',');
html = '<tr>';
for(col = 0; col < cols.length; col++) {
html += '<td>'+cols[col]+'</td>';
}
html += '</tr>';
output.append(html);
}
}
};
// Read in the text file
reader.readAsBinaryString(f);
}
});
您可以从CSV文件的内容生成HTML表格(这是基于这个优秀的网站)
You can generate an HTML table from the contents of a CSV file (this is based on this excellent site)
这篇关于带路径的JS $ .get方法文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!