有没有人知道从CSV文件获取数据的方法,然后将其放入一个我可以通过AJAX传递到我的网络服务的数组中?
答案 0 :(得分:1)
用一个不错的jQuery解决方案取代了我的整个答案:
$(document).ready(function() {
var data = '"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE" "1985/01/21","Douglas Adams",0345391802,5.95 "1990/01/12","Douglas Hofstadter",0465026567,9.95 "1998/07/15","Timothy ""The Parser"" Campbell",0968411304,18.99 "1999/12/03","Richard Friedman",0060630353,5.95 "2001/09/19","Karen Armstrong",0345384563,9.95 "2002/06/23","David Jones",0198504691,9.95 "2002/06/23","Julian Jaynes",0618057072,12.50 "2003/09/30","Scott Adams",0740721909,4.95 "2004/10/04","Benjamin Radcliff",0804818088,4.95 "2004/10/04","Randel Helms",0879755725,4.50';
var array1 = data.split("\t");
var array2 = new Array();
for (var i = 0; i < array1.length; i++) {
array2.push(array1[i].split(","));
for (var j = 0; j < array2[i].length; j++) {
$('ul').append('<li>'+array2[i][j]+'</li>');
}
$('ul').append('<li><hr></li>');
}
});
唯一的区别是您必须执行以下操作才能检索CSV文件...
$.ajax({
url: "file.csv",
success: function(data) {
var array1 = data.split("\t");
var array2 = new Array();
for (var i = 0; i < array1.length; i++) {
array2.push(array1[i].split(","));
for (var j = 0; j < array2[i].length; j++) {
$('ul').append('<li>'+array2[i][j]+'</li>');
}
$('ul').append('<li><hr></li>');
}
}
});
答案 1 :(得分:1)
FileReference和FileAPI是大多数现代浏览器都可用的库。收到文件并以字符数组的形式访问它后,您可以应用正则表达式或拆分。
一个例子:
// this first part is from FileAPI
// it allows you access to files that
// the user has selected
var file = $('#file').get().files[0];
data = getAsText(file);
// assuming you'll use a semicolon as separator
// and you're not forcing all fields to be quoted
var an_array = data.split(";");
$.post('script.php', an_array, function(response) {
// Do something with the response
}, 'json');
getAsText()
函数不是API的一部分,我从here读取它并且没有理由完全复制它。