簡體   English   中英

javaScript文件加載順序錯誤

[英]javaScript file loads in wrong order

我是javaScript的新手,正在嘗試將CS​​V或TXT文件加載到瀏覽器中。

選擇文件后,事件處理程序將顯示文件名和詳細信息,一旦用戶單擊加載按鈕,腳本應仔細檢查文件擴展名,加載文件,然后對文件進行進一步檢查。

我的問題是文件加載函數似乎總是被調用為最后,這意味着其他檢查首先發生。

該文件位於此處: http : //bananamountain.net/project/20140703pm/file-loader2.html

代碼粘貼如下:

</head>
<body>

    <script>
        // Check for the various File API support.
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            // Great success! All the File APIs are supported.
        } else {
            alert('The File APIs are not fully supported in this browser.');
        }

    </script>
    <h3>File Load test</h3>
    <p>Use only test-data-csv.csv just now</p>
    <input type="file" id="file" name="file" required="required" accept=".csv, .txt" />
    <button onclick="handleFileLoad()">Load button</button>

    <output id="list"></output>

    <script>

        // global variables
        var content;
        var fileName;
        var splitString = ",";
        var rows = new Array();
        var headerRow = new Array();
        var values = new Array();

        function handleFileLoad() {
            //var suitableFileType = checkFileType();
            //document.write("<strong>Suitable file type: " + suitableFileType + "</strong><br />");


            loadFile();
            var suitableContent = checkFileContent();
            document.write("<strong>Suitable file content: " + suitableContent + "</strong><br />");


        }


        function checkFileType() {      
            document.write("inside checkFileType<br/>");
            // var testFile = fileName.split(".")[1].toUpperCase();
            //    document.write("file extension is '" + testFile+ "'<br />");

            if ((fileName.split(".")[1].toUpperCase() === "CSV")) { 
                document.write('suitable file selected<br/>');
                return (true);
            } else if (fileName.split(".")[1].toUpperCase() === "TXT") {
                document.write('suitable file selected<br/>');
                return (true);
            }else {
                document.write('Invalid file format! \nPlease select a suitable .txt or .csv file<br/>');
                return (false);
            }

        }   // end of checkFileType - tested WORKING

        function loadFile() {

            //  checkFileType();

            var file = document.getElementById("file").files[0];
            var reader = new FileReader();
            var link_reg = /(http:\/\/|https:\/\/)/i;
            reader.onload = function(file) {
                // content = reader.result;
                content = file.target.result;
                rows = file.target.result.split(/[\r\n|\n]+/);
                for (var i=0; i<rows.length; i++) {
                    document.write("row found at line " + i + " is " + rows[i] +".<br/>");
                }
            };
            reader.readAsText(file);
            /*
            var suitableFileType = checkFileType();
            document.write("<strong>Suitable file type: " + suitableFileType + "</strong><br />");

            var suitableContent = checkFileContent();
            document.write("<strong>Suitable file content: " + suitableContent + "</strong><br />");

            var splitStringFound = getSplitString();
            document.write("<strong>Split string found: " + splitStringFound + "</strong><br />");
            document.write("<strong>Split String: " + splitString + "</strong><br/>");

            var replacedHeaders = checkHeaderRow();
            document.write("<strong>Header row complete<br />" + replacedHeaders +" headers replaced</strong><br/>");

            document.write(content);

            document.write(fileName);
            document.write(splitString);
            document.write(rows);
            document.write( headerRow);
            document.write(values);*/
            return;
        }


        function checkFileContent() {

            document.write("inside check file content<br/>");
            // check for file content
            // identifies blank lines and deletes them

            // checking content of rows
            for (var i=0;i<rows.length;i++) {
                document.write ("Row " + i + " is " + rows[i]);
            }
            var filteredArr = rows.filter(function (val) {
                return !(val === "" || typeof val == "undefined" || val === null || val === ",," || val === "\t\t");
            });

            // identifies empty file (e.g. all blank lines deleted)
            if (filteredArr.length === 0) {
                document.write("Empty file - no data found <br/>");
                rows = filteredArr;
                return false;
                // check for row deletions
            } else if (rows.length < filteredArr.length) {
                rows = filteredArr;
                document.write("blank rows deleted - " + (rows.length - filteredArr.length) + " rows remaining. <br/>");
                return ("deletions");
            } else {
                document.write("No blank rows <br/>");
                return true;
            }
        }       // end of check file content - empty file tested, file with one line tested

        function checkHeaderRow() {
            // check for header row
            // words in first non-empty row
            var replaceCount = 0;
            var checkArray = rows[0].split(splitString);

            for (var i = 1; i < checkArray.length; i++) {
                // start at array[1] as array[0] not likely to be a header value
                // loop through inserting non numeric values into headerRow array
                if (isNaN(checkArray[i])) {
                    headerRow[i - 1] = checkArray[i];
                    // need a flag to remove this from file once it has been done
                    replaceCount++;
                } else {
                    headerRow[i - 1] = "Risk " + i;
                }
            }
            // if non numeric values in array[1] delete rows[0]
            // so the header row is not included with the data set
            if (isNaN(checkArray[1])) {
                rows[0] = null;
            }
            return (replaceCount);
        }  // end of checkHeaderRow works for all non-numeric, all numeric and mixed


        function getSplitString() {

            // call countCharacter to return count of comma and tab characters in first five lines
            var tabCount =  countCharacter("\t");
            var commaCount = countCharacter(",");

            // compare tabCount and commaCount values
            if (tabCount === 0 && commaCount === 0) {
                document.write("Cannot detect the value seperator,\n please ammend file to seperate values with tabs or commas");
                return false;
            }
            else if (tabCount === commaCount) {
                splitString = prompt("Cannot detect the value seperator,\n please input \"\\t\" for tabs or \",\" for commas");
                if ((splitString === null) || (splitString != '\t') || (splitString != ',')) {
                    document.write("please check file and try again<br/>");
                    splitString = ',';
                    return false;  
                }   // NOT WORKING
                else {
                    return true;
                }
            } else if (tabCount>commaCount) {
                splitString = "\t";
                if (commaCount!=0) {
                    document.write("tab character selected as value seperator.<br/>");
                    // alert as this may not be the case
                }
                return true;
            } else {
                splitString=",";
                if (tabCount!=0){
                    document.write("tab character selected as value seperator.<br/>");
                    // alert as this may not be the case
                }
                return true;
            }
        }       // end of getSplitString - NOT FULLY WORKING


        function splitRows() {
            // what if rows is now empty? (e.g. header row only in file)
            if (rows[0] != null) {
                for (var i=0; i<rows.length;i++) {
                    values.push(rows[i].split(splitString));
                }
                return values;
            } else {
                return false;
            }
        }  // end of splitRows fully working

        function checkEmptyCells () {


            for (var i=0; i<values.length; i++) {
                for (var j=0; j<values[i].length; j++)
                    if (!((values[i][j] === "") || (typeof values[i][j] == "undefined") || (values[i][j] === null) || (values[i][j] === ",,") || (values[i][j] === "\t\t"))) {
                        // remove line values[i][j]
                        document.write("in here");
                    }
            }
        }   // NOT FININSHED - STOPPED HERE



        function countCharacter (character) {
            // count the instances of a specified character over first 5 lines (or length of rows array)
            // number of rows to loop through 
            var loopCount=0;
            var characterCount=0;

            if (rows.length < 5) {
                loopCount = rows.length;
            } else {
                loopCount = 5;
            }
            for (var count=0; count < loopCount; count++) {
                characterCount += rows[count].split(character).length-1;

            }
            return characterCount;
        }  // End of countCharacter - WORKING - TESTED







        function handleFileSelect(evt) {
            var files = evt.target.files; // FileList object

            // files is a FileList of File objects. List some properties.
            var output = [];
            for (var i = 0, f; f = files[i]; i++) {     // THIS IS NOT NEEDING TO BE IN A LOOP
                output.push('<strong>', escape(f.name), '</strong> ', ' - ',
                            f.size, ' bytes, last modified: ',
                            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                            '');
                fileName = escape(f.name);
            }
            document.getElementById('list').innerHTML = '<div class="file-name">' + output.join('') + '</div>';
        }

        document.getElementById('file').addEventListener('change', handleFileSelect, false);

    </script>


</body>
</html>

因此,首先我想我問的問題錯了,正是由於這個原因,答復有限。 我正在添加答案,以便如果有人遇到相同的問題並遇到此問題,它可以為他們提供幫助。

問題出在html文件加載中,而不是在通過javascript文件加載中。 該腳本對文件進行了一些檢查,加載了文件,然后對文件的內容進行了進一步檢查。

一切都正確地進行了,但是javascript進行了一種稱為“異步加載”的操作,在該過程中它依次調用函數,但是在當前函數完成其工作之前移至下一個函數。

想象一下,您去了一家酒吧,點了杯飲料,支付了酒水,然后去了餐桌。 Javascript可以做到這一點,但沒有通常的等待服務,飲料使用和零錢的暫停。

從本質上講,我的代碼是不帶飲料返回表(或在文件未完成加載的情況下檢查文件的內容)。

為了解決這個問題,我超時了,這可能不是最好的,因為加載速度將取決於文件的大小。 但是,它現在才起作用,並允許我繼續進行其他工作。

工作代碼段如下:{function handleFileLoad(){

            if (checkFileType()) {
                values = [];
                loadFile();
            } else {
                alert("Invalid file format! \nPlease select a suitable .txt or .csv file<br/>");
                return;
            }

            //setTimeout(fileContentChecks(), 1000);

            if (!setTimeout(fileContentChecks(), 1000)) {
                return;
            } else {
                setData(); //PROBABLY PUT THESE IN A FUNCTION OR TWO
                setComboLists(); //SO THESE CAN BE CALLED LATER TO UPDATE PAGE
                UpdateAssetList();
                UpdateXAxisList();
                UpdateYAxisList();
                UpdateTable();
            }
        }


        function checkFileType() { // CHECK FILE NAME EXTENSION

            if ((fileName.split(".")[1].toUpperCase() === "CSV")) {
                return (true);
            } else if (fileName.split(".")[1].toUpperCase() === "TXT") {
                return (true);
            } else {
                return (false);
            }
        } // end of checkFileType - tested WORKING


        function loadFile() { // LOADS FILE AND SPLITS INTO ROWS

            var file = document.getElementById("file").files[0];
            var reader = new FileReader();
            var link_reg = /(http:\/\/|https:\/\/)/i;
            reader.onload = function(file) {

                content = file.target.result;
                rows = file.target.result.split(/[\r\n|\n]+/);
            };
            reader.readAsText(file);
            // NEEDS TIMEOUT HERE.....
            return;
        } // end of loadFile - TESTED WORKS WHEN STEPPING THROUGH - NEEDS TIMEOUT

        function fileContentChecks() {
            if (checkFileContent()) {
                if (getSplitString()) {
                    checkHeaderRow();
                } else {
                    alert("Seperator value not found"); // not sure if this is required?
                    return false;
                }
            } else {
                alert("File contents not verified, please check file and try again.");
                return false;
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM