最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I pull data from a CSV file and populate an HTML table with it? - Stack Overflow

programmeradmin3浏览0评论

So, I have seen similar questions, but I haven't been able to get a working answer. Everyday a pany is going to FTP a file to our server. We already know the file name and where it will go on the server. Our job is to take the data and insert it into an HTML table. Inserting the data is the easy part, it's getting the data that has been the problem. If I can just get the entire CSV file (it only has 4 values) as a string, I would be able to do it using regex.

I tried to make an XMLHTTPRequest with AJAX, and then use responseText to get the data as the string. After having no luck there, I tried to use JQuery to get it. This is my code, but I always get 'An error occurred' logged to the console. I am thinking maybe it just can't process the csv file. Also, file.csv is in the same directory as index.aspx right now, hence the file path you see in the code. We don't want to cache the file since it gets updated daily. Thanks for your help.

NOTE: The code below has been corrected. If you have a similar problem, this code should work for you. Make sure you double check your file path and do not use 'dataType: type' in the $.ajax block.

 // Wait for the DOM to be ready
        $(document).ready(function() {
            // Use JQuery promises to make AJAX XMLHttpRequest
            promise = $.ajax({
                type:"GET",
                url:"file.csv",
                cache:false
            });

            // Run script when file is ready
            promise.done(function(data){
                console.log(data);

                // Table IDs represented as an array
                var ids = ['date', 'fund', 'change', 'points'];

                // Update table
                for (var x = 0; x < ids.length; x++) {
                    document.getElementById(ids[x]).innerHTML = data[x];
                }
            });

            // Run script if request fails
            promise.fail(function() {
                console.log('A failure ocurred');
            });

        });

So, I have seen similar questions, but I haven't been able to get a working answer. Everyday a pany is going to FTP a file to our server. We already know the file name and where it will go on the server. Our job is to take the data and insert it into an HTML table. Inserting the data is the easy part, it's getting the data that has been the problem. If I can just get the entire CSV file (it only has 4 values) as a string, I would be able to do it using regex.

I tried to make an XMLHTTPRequest with AJAX, and then use responseText to get the data as the string. After having no luck there, I tried to use JQuery to get it. This is my code, but I always get 'An error occurred' logged to the console. I am thinking maybe it just can't process the csv file. Also, file.csv is in the same directory as index.aspx right now, hence the file path you see in the code. We don't want to cache the file since it gets updated daily. Thanks for your help.

NOTE: The code below has been corrected. If you have a similar problem, this code should work for you. Make sure you double check your file path and do not use 'dataType: type' in the $.ajax block.

 // Wait for the DOM to be ready
        $(document).ready(function() {
            // Use JQuery promises to make AJAX XMLHttpRequest
            promise = $.ajax({
                type:"GET",
                url:"file.csv",
                cache:false
            });

            // Run script when file is ready
            promise.done(function(data){
                console.log(data);

                // Table IDs represented as an array
                var ids = ['date', 'fund', 'change', 'points'];

                // Update table
                for (var x = 0; x < ids.length; x++) {
                    document.getElementById(ids[x]).innerHTML = data[x];
                }
            });

            // Run script if request fails
            promise.fail(function() {
                console.log('A failure ocurred');
            });

        });
Share Improve this question edited Jun 12, 2015 at 15:54 dyachenko 1,21214 silver badges29 bronze badges asked Jun 12, 2015 at 14:43 Joseph BergmanJoseph Bergman 491 silver badge5 bronze badges 9
  • Since your URL is relative (i.e. "file.csv"), have you checked it's not just a simple 404 error? The path could just be wrong? In the network tab of developer tools in your browser, check the full details of the request you're making to file.csv. Cut out the javascript for now, just navigate directly to that csv and make sure the path is good. – user1017882 Commented Jun 12, 2015 at 14:53
  • @JayMee is probably right; the other thing I'd check is if the server running the code can access the file system it's on - if it's a network file system, it may be password protected which could cause issues. – Brian Commented Jun 12, 2015 at 14:57
  • ...I don't think that jQuery has a CSV parser... – Frogmouth Commented Jun 12, 2015 at 14:57
  • 1 dataType:"text/csv" is wrong. you need to use dataType:"text". – Frogmouth Commented Jun 12, 2015 at 15:04
  • 1 For your knowledge, function called by.fail() method has 3 attributes: jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); that can help you to debug the request. WIth text/csv like dataType the attribute textStatus is parsererror – Frogmouth Commented Jun 12, 2015 at 15:11
 |  Show 4 more ments

1 Answer 1

Reset to default 3

I was able to get it working by changing the dataType:"text".

Also included the code to parse the csv file.

$(document).ready(function() {

    promise = $.ajax({
        type:"GET",
        dataType:"text",
        url:"file.csv",
        cache:false
    });

    promise.done(function(data){

        //Parse CSV File
        //split on new line
        var dataArr = data.split("\n");

        //for each line in array
        $.each(dataArr,function(){
            if (this != "") {

                //split files and create row
                var row = new String("");
                valArr = this.split(",");
                    row += "<tr>"

                $.each(valArr, function(){
                    row += "<td>" + this +"</td>"
                });     

                    row += "</tr>"

                    //Add row to table
                    $('tbody').append(row);

            }

        });

    });

    // Run script if request fails
    promise.fail(function() {
       console.log('A failure ocurred');
    });

});

HTML:

<table class="table table-hover">
    <thead>
        <tr>
            <th>Date</th>
            <th>Fund</th>
            <th>Change</th>
            <th>Points</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

发布评论

评论列表(0)

  1. 暂无评论