1

有谁知道从 CSV 文件中获取数据的方法,然后将其放入可以通过 AJAX 传递给我的网络服务的数组中?

4

2 回答 2

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>');
        }
      }
    });
于 2012-08-30T12:12:32.800 回答
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 的一部分,我从这里读到它,没有理由完全复制它。

搜索我可以使用。com

于 2012-08-30T12:13:23.963 回答