无法使用jquery加载csv文件

时间:2017-11-21 14:15:36

标签: javascript jquery html csv

我正在尝试从名为stores.csv的文件加载数据但无法加载。 在这里,我发布了我的代码,csv文件名称为read.csv,所以请帮我解决问题。

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Read Data from Text File into Objects and Output as Table</title>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script>

<body>
    <h1>Pull data from CSV file into an object and output as table</h1>
    <div class="result">
        <table id="theResult" border="1"></table>
    </div>
</body>
<script>
    $(document).ready(function () {
        $.get('stores.csv', function (theData) {
            var data = $.csv.toObjects(theData);
            var theHtml = createTable(data);
            $('#theResult').html(theHtml);
        });
    });

    function createTable(data) {
        var html = '';

        if (data[0].constructor === Object) {
            html += '<tr>\r\n';
            for (var item in data[0]) {
                html += '<th>' + item + '</th>\r\n';
            }
            html += '</tr>\r\n';

            for (var row in data) {
                html += '<tr>\r\n';
                for (var item in data[row]) {
                    html += '<td>' + data[row][item] + '</td>\r\n';
                }
                html += '</tr>\r\n';
            }
        }
        return html;
    }
</script>

</html>

enter image description here

1 个答案:

答案 0 :(得分:1)

您用于jquery.csv.js的网址不再存在,并引发404。所以你的错误在

$.csv.toObjects(theData);

您应该将网址更改为此CDN链接

https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.8.3/jquery.csv.min.js

所以基本上你的标签会改变

<script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.8.3/jquery.csv.min.js"></script>